-
-
Save CoXier/7528d0732191dafccfe0d5b934574c10 to your computer and use it in GitHub Desktop.
Curl okhttp api request
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import okhttp3.*; | |
import okio.Buffer; | |
import java.io.IOException; | |
import java.nio.charset.Charset; | |
public class CurlLoggerInterceptor implements Interceptor { | |
private StringBuilder curlCommandBuilder; | |
private final Charset UTF8 = Charset.forName("UTF-8"); | |
private String tag = null; | |
public CurlLoggerInterceptor() { | |
} | |
/** | |
* Set logcat tag for curl lib to make it ease to filter curl logs only. | |
* @param tag | |
*/ | |
public CurlLoggerInterceptor(String tag) { | |
this.tag = tag; | |
} | |
@Override | |
public Response intercept(Chain chain) throws IOException { | |
Request request = chain.request(); | |
curlCommandBuilder = new StringBuilder(""); | |
// add cURL command | |
curlCommandBuilder.append("cURL "); | |
curlCommandBuilder.append("-X "); | |
// add method such as Get/POST | |
curlCommandBuilder.append(request.method().toUpperCase()).append(" "); | |
// adding headers | |
for (String headerName : request.headers().names()) { | |
addHeader(headerName, request.headers().get(headerName)); | |
} | |
// adding request body | |
if (request.body() != null) { | |
RequestBody requestBody = request.body(); | |
Buffer buffer = new Buffer(); | |
requestBody.writeTo(buffer); | |
Charset charset; | |
MediaType contentType = requestBody.contentType(); | |
if (contentType != null) { | |
addHeader("Content-Type", request.body().contentType().toString()); | |
charset = contentType.charset(UTF8); | |
curlCommandBuilder.append(" -d '").append(buffer.readString(charset)).append("'"); | |
} | |
} | |
// add request URL | |
curlCommandBuilder.append(" \"").append(request.url().toString()).append("\""); | |
curlCommandBuilder.append(" -L"); | |
CurlPrinter.print(tag, request.url().toString(), curlCommandBuilder.toString()); | |
return chain.proceed(request); | |
} | |
private void addHeader(String headerName, String headerValue) { | |
curlCommandBuilder.append("-H " + "\"").append(headerName).append(": ").append(headerValue).append("\" "); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment