forked from Kong/httpsnippet
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathokhttp.js
More file actions
78 lines (64 loc) · 2.23 KB
/
okhttp.js
File metadata and controls
78 lines (64 loc) · 2.23 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
/**
* @description
* HTTP code snippet generator for Java using OkHttp.
*
* @author
* @shashiranjan84
*
* for any questions or issues regarding the generated code snippet, please open an issue mentioning the author.
*/
'use strict'
var CodeBuilder = require('../../helpers/code-builder')
module.exports = function (source, options) {
var opts = Object.assign({
indent: ' '
}, options)
var code = new CodeBuilder(opts.indent)
var methods = ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD']
var methodsWithBody = ['POST', 'PUT', 'DELETE', 'PATCH']
code.push('OkHttpClient client = new OkHttpClient();')
.blank()
if (source.postData.text) {
if (source.postData.boundary) {
code.push('MediaType mediaType = MediaType.parse("%s; boundary=%s");', source.postData.mimeType, source.postData.boundary)
} else {
code.push('MediaType mediaType = MediaType.parse("%s");', source.postData.mimeType)
}
code.push('RequestBody body = RequestBody.create(mediaType, %s);', JSON.stringify(source.postData.text))
}
code.push('Request request = new Request.Builder()')
code.push(1, '.url("%s")', source.fullUrl)
if (methods.indexOf(source.method.toUpperCase()) === -1) {
if (source.postData.text) {
code.push(1, '.method("%s", body)', source.method.toUpperCase())
} else {
code.push(1, '.method("%s", null)', source.method.toUpperCase())
}
} else if (methodsWithBody.indexOf(source.method.toUpperCase()) >= 0) {
if (source.postData.text) {
code.push(1, '.%s(body)', source.method.toLowerCase())
} else {
code.push(1, '.%s(null)', source.method.toLowerCase())
}
} else {
code.push(1, '.%s()', source.method.toLowerCase())
}
// Add headers, including the cookies
var headers = Object.keys(source.allHeaders)
// construct headers
if (headers.length) {
headers.forEach(function (key) {
code.push(1, '.addHeader("%s", "%s")', key, source.allHeaders[key])
})
}
code.push(1, '.build();')
.blank()
.push('Response response = client.newCall(request).execute();')
return code.join()
}
module.exports.info = {
key: 'okhttp',
title: 'OkHttp',
link: 'http://square.github.io/okhttp/',
description: 'An HTTP Request Client Library'
}