|
| 1 | +/** |
| 2 | + * @description |
| 3 | + * HTTP code snippet generator for Java using Unirest. |
| 4 | + * |
| 5 | + * @author |
| 6 | + * @shashiranjan84 |
| 7 | + * |
| 8 | + * for any questions or issues regarding the generated code snippet, please open an issue mentioning the author. |
| 9 | + */ |
| 10 | + |
| 11 | +'use strict' |
| 12 | + |
| 13 | +var util = require('util') |
| 14 | +var CodeBuilder = require('../../helpers/code-builder') |
| 15 | + |
| 16 | +module.exports = function (source, options) { |
| 17 | + var opts = util._extend({ |
| 18 | + indent: ' ' |
| 19 | + }, options) |
| 20 | + |
| 21 | + var code = new CodeBuilder(opts.indent) |
| 22 | + |
| 23 | + var methods = [ 'GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD', 'OPTIONS' ] |
| 24 | + |
| 25 | + if (methods.indexOf(source.method.toUpperCase()) === -1) { |
| 26 | + return 'Method not supported' |
| 27 | + } |
| 28 | + |
| 29 | + if (source.postData.text) { |
| 30 | + RequestBody body = RequestBody.create(JSON, json); |
| 31 | + code.push(1, 'RequestBody body = RequestBody.create("%s", %s);', source.postData.mimeType, JSON.stringify(source.postData.text)) |
| 32 | + } |
| 33 | + |
| 34 | + code.push('Request request = new Request.Builder()') |
| 35 | + code.push('.url("%s")', source.fullUrl) |
| 36 | + if(source.postData.text){ |
| 37 | + code.push(1,'.%s(body)', source.method) |
| 38 | + }else{ |
| 39 | + code.push(1,'.%s()', source.method) |
| 40 | + } |
| 41 | + |
| 42 | + // Add headers, including the cookies |
| 43 | + var headers = Object.keys(source.allHeaders) |
| 44 | + |
| 45 | + // construct headers |
| 46 | + if (headers.length) { |
| 47 | + headers.map(function (key) { |
| 48 | + code.push(1, '.addHeader("%s", "%s")', key, source.allHeaders[key]) |
| 49 | + }) |
| 50 | + } |
| 51 | + |
| 52 | + code.push(1, '.build();') |
| 53 | + |
| 54 | + code.push('Response response = client.newCall(request).execute();') |
| 55 | + |
| 56 | + return code.join() |
| 57 | +} |
| 58 | + |
| 59 | +module.exports.info = { |
| 60 | + key: 'okhttp', |
| 61 | + title: 'OkHttp', |
| 62 | + link: 'http://square.github.io/okhttp/', |
| 63 | + description: 'An HTTP Request Client Library' |
| 64 | +} |
0 commit comments