protected String doInBackground(ArrayList<String>... args) { ArrayList<String> l = args[0]; String value = l.get(1); String fileName = l.get(0); System.out.println(value); System.out.println(fileName); try { OkHttpClient client = new OkHttpClient(); RequestBody formBody = new FormBody.Builder().add("texte", value).add("fichier", fileName).build(); Request request = new Request.Builder() .url("http://theprintmint-framing.com/tp2/writefile.php") .post(formBody) .build(); Response response = client.newCall(request).execute(); if (!response.isSuccessful()) throw new IOException("Unexpected code " + response); System.out.println(response.body().string()); } catch (Exception e) { e.printStackTrace(); } return null; }
public ServerInfoJson getServerInfo(HttpUrl serverUrl, String serverID, String id) throws IOException { // set timeout to 30 seconds OkHttpClient client = defaultClient .newBuilder() .connectTimeout(30, TimeUnit.SECONDS) .readTimeout(30, TimeUnit.SECONDS) .build(); JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("version", 1); jsonObject.addProperty("command", "get_server_info"); jsonObject.addProperty("stop_when_error", "false"); jsonObject.addProperty("stop_when_success", "false"); jsonObject.addProperty("id", id); jsonObject.addProperty("serverID", serverID); RequestBody requestBody = RequestBody.create(MediaType.parse("text/plain"), gson.toJson(jsonObject)); Request request = new Request.Builder().url(serverUrl).post(requestBody).build(); Response response = client.newCall(request).execute(); InputStream in = response.body().byteStream(); JsonReader reader = null; ServerInfoJson serverInfoJson = null; try { reader = new JsonReader(new InputStreamReader(in, "UTF-8")); serverInfoJson = gson.fromJson(reader, ServerInfoJson.class); } finally { if (reader != null) { reader.close(); } } if (serverInfoJson != null) { if (serverInfoJson.server != null) { // server info found! return serverInfoJson; } else if (serverInfoJson.sites != null && !serverInfoJson.sites.isEmpty()) { String site = serverInfoJson.sites.get(0); return getServerInfo( new HttpUrl.Builder().scheme("http").host(site).addPathSegment("Serv.php").build(), serverID, id); } } throw new IOException("No server info found!"); }
@Test public void proxySelector() throws Exception { server.enqueue(new MockResponse().setBody("abc")); ProxySelector proxySelector = new ProxySelector() { @Override public List<Proxy> select(URI uri) { return Collections.singletonList(socksProxy.proxy()); } @Override public void connectFailed(URI uri, SocketAddress socketAddress, IOException e) { throw new AssertionError(); } }; OkHttpClient client = new OkHttpClient.Builder().setProxySelector(proxySelector).build(); Request request = new Request.Builder().url(server.url("/")).build(); Response response = client.newCall(request).execute(); assertEquals("abc", response.body().string()); assertEquals(1, socksProxy.connectionCount()); }
public void execute(String url, final IRespListener listener) { RequestBody reqBody = builder.build(); Request req = new Request.Builder().url(url).post(reqBody).build(); OkHttpClient http = new OkHttpClient(); http.newCall(req) .enqueue( new Callback() { @Override public void onFailure(final Call call, final IOException e) { Log.d("szw", "http error : " + e); handler.post( new Runnable() { @Override public void run() { listener.onHttpFail(call, e); } }); } @Override public void onResponse(final Call call, final Response response) throws IOException { handler.post( new Runnable() { @Override public void run() { try { listener.onHttpResp(call, response.body().string()); } catch (IOException e) { e.printStackTrace(); } } }); } }); }
public Request testSSL(Context context, final OnResultListener<String> listener) { Request request = new Request.Builder().url("https://192.168.210.51:8443/test.html").build(); final CallbackObject<String> callbackObject = new CallbackObject<String>(); callbackObject.request = request; callbackObject.listener = listener; mClient .newCall(request) .enqueue( new Callback() { @Override public void onFailure(Call call, IOException e) { callbackObject.exception = e; Message msg = mHandler.obtainMessage(MESSAGE_FAILURE, callbackObject); mHandler.sendMessage(msg); } @Override public void onResponse(Call call, Response response) throws IOException { callbackObject.result = response.body().string(); Message msg = mHandler.obtainMessage(MESSAGE_SUCCESS, callbackObject); mHandler.sendMessage(msg); } }); return request; }
/** * 将Json转为Bean * * @param tag * @param url * @param headers * @param beanClass * @param getBeanCallBack * @param <T> */ public static <T> void getBean( Object tag, String url, Map<String, String> headers, final Class<T> beanClass, final GetBeanCallBack<T> getBeanCallBack) { Logger.i(TAG, "getBean url:" + url); setCancel(false); if (mClient != null) { Request.Builder requestBuilder = new Request.Builder(); requestBuilder.tag(tag); requestBuilder.url(url); appendHeaders(requestBuilder, headers); Request request = requestBuilder.build(); mCall = mClient.newCall(request); mCalls.add(mCall); mCall.enqueue( new Callback() { @Override public void onFailure(Call call, IOException e) { Logger.e(TAG, "getBean onFailure" + e.getMessage()); EventBus.getDefault().post(new NetWorkBadEvent()); getBeanCallBack.onFailure(call, e); } @Override public void onResponse(Call call, Response response) throws IOException { if (response.isSuccessful()) { getBeanCallBack.onResponse(GsonUtils.fromJson(response.body().string(), beanClass)); } } }); } }
public static int UserMatch() throws IOException, JSONException { if (android.os.Build.VERSION.SDK_INT > 9) { StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); } OkHttpClient client = new OkHttpClient(); RequestBody formBody = new FormBody.Builder().add("username", username).add("password", password).build(); Request request = new Request.Builder() .url("http://projetdeweb.azurewebsites.net/API/Connection/Connect") .post(formBody) .build(); Response response = client.newCall(request).execute(); if (!response.isSuccessful()) throw new IOException("Unexpected code " + response); System.out.println(response.body().string()); int Rights = -1; JSONArray jsonArray = new JSONArray(response.body().string()); for (int i = 0; i < jsonArray.length(); i++) { JSONObject jsonObject = jsonArray.getJSONObject(i); Rights = jsonObject.optInt("Rights"); } return Rights; }
/** * base 的 get请求 * * @param tag * @param url * @param headers * @param getCallBack */ public static void get( Object tag, String url, Map<String, String> headers, final GetCallBack getCallBack) { Logger.i(TAG, "get url :" + url); setCancel(false); if (mClient != null) { Request.Builder requestBuilder = new Request.Builder(); requestBuilder.tag(tag); requestBuilder.url(url); appendHeaders(requestBuilder, headers); Request request = requestBuilder.build(); mCall = mClient.newCall(request); mCalls.add(mCall); mCall.enqueue( new Callback() { @Override public void onFailure(Call call, IOException e) { getCallBack.onFailure(call, e); Logger.e(TAG, "get onFailure:" + e.getMessage()); EventBus.getDefault().post(new NetWorkBadEvent()); } @Override public void onResponse(Call call, Response response) throws IOException { if (response.isSuccessful()) { getCallBack.onResponse(call, response); } else { getCallBack.onError(response.toString()); } } }); } }
private String authorize() { try { OkHttpClient.Builder builder = client.newBuilder(); builder.interceptors().remove(this); OkHttpClient clone = builder.build(); String credential = Credentials.basic(config.getUsername(), new String(config.getPassword())); URL url = new URL(URLUtils.join(config.getMasterUrl(), AUTHORIZE_PATH)); Response response = clone .newCall( new Request.Builder().get().url(url).header(AUTHORIZATION, credential).build()) .execute(); response.body().close(); response = response.priorResponse() != null ? response.priorResponse() : response; response = response.networkResponse() != null ? response.networkResponse() : response; String token = response.header(LOCATION); if (token == null || token.isEmpty()) { throw new KubernetesClientException( "Unexpected response (" + response.code() + " " + response.message() + "), to the authorization request. Missing header:[" + LOCATION + "]!"); } token = token.substring(token.indexOf(BEFORE_TOKEN) + BEFORE_TOKEN.length()); token = token.substring(0, token.indexOf(AFTER_TOKEN)); return token; } catch (Exception e) { throw KubernetesClientException.launderThrowable(e); } }
public static byte[] postGetByte(String url, String json) throws IOException { RequestBody formBody = new FormBody.Builder().add("search", "Jurassic Park").build(); Request request = new Request.Builder().url(url).post(formBody).build(); Response response = client.newCall(request).execute(); if (response.isSuccessful()) { return response.body().bytes(); } return null; }
@Test public void proxy() throws Exception { server.enqueue(new MockResponse().setBody("abc")); server.enqueue(new MockResponse().setBody("def")); OkHttpClient client = new OkHttpClient.Builder().setProxy(socksProxy.proxy()).build(); Request request1 = new Request.Builder().url(server.url("/")).build(); Response response1 = client.newCall(request1).execute(); assertEquals("abc", response1.body().string()); Request request2 = new Request.Builder().url(server.url("/")).build(); Response response2 = client.newCall(request2).execute(); assertEquals("def", response2.body().string()); // The HTTP calls should share a single connection. assertEquals(1, socksProxy.connectionCount()); }
/** * 同步POST * * @param url 请求的url * @param params 参数 * @return */ public static String synRequestServerByPost(final String url, JSONObject params) { throwException(); Request request = requestFactory(url, params, true); try { Response response = mOkHttpClient.newCall(request).execute(); return response.body().string(); } catch (IOException e) { e.printStackTrace(); } return ""; }
public void run() throws Exception { Request request = new Request.Builder().url("http://publicobject.com/helloworld.txt").build(); Response response1 = client.newCall(request).execute(); if (!response1.isSuccessful()) throw new IOException("Unexpected code " + response1); String response1Body = response1.body().string(); System.out.println("Response 1 response: " + response1); System.out.println("Response 1 cache response: " + response1.cacheResponse()); System.out.println("Response 1 network response: " + response1.networkResponse()); Response response2 = client.newCall(request).execute(); if (!response2.isSuccessful()) throw new IOException("Unexpected code " + response2); String response2Body = response2.body().string(); System.out.println("Response 2 response: " + response2); System.out.println("Response 2 cache response: " + response2.cacheResponse()); System.out.println("Response 2 network response: " + response2.networkResponse()); System.out.println("Response 2 equals Response 1? " + response1Body.equals(response2Body)); }
private InputStream prepareConnection() throws IOException { Request request = new Request.Builder().url(url).build(); Response response = CLIENT.newCall(request).execute(); if (response.code() != 200) { Log.e("ERROR", "Server returned HTTP " + response.message()); return null; } return response.body().byteStream(); }
public void run() throws Exception { File file = new File("README.md"); Request request = new Request.Builder() .url("https://api.github.com/markdown/raw") .post(RequestBody.create(MEDIA_TYPE_MARKDOWN, file)) .build(); Response response = client.newCall(request).execute(); if (!response.isSuccessful()) throw new IOException("Unexpected code " + response); System.out.println(response.body().string()); }
@Override public long open(DataSpec dataSpec) throws HttpDataSourceException { this.dataSpec = dataSpec; this.bytesRead = 0; this.bytesSkipped = 0; Request request = makeRequest(dataSpec); try { response = okHttpClient.newCall(request).execute(); responseByteStream = response.body().byteStream(); } catch (IOException e) { throw new HttpDataSourceException( "Unable to connect to " + dataSpec.uri.toString(), e, dataSpec); } int responseCode = response.code(); // Check for a valid response code. if (!response.isSuccessful()) { Map<String, List<String>> headers = request.headers().toMultimap(); closeConnectionQuietly(); throw new InvalidResponseCodeException(responseCode, headers, dataSpec); } // Check for a valid content type. MediaType mediaType = response.body().contentType(); String contentType = mediaType != null ? mediaType.toString() : null; if (contentTypePredicate != null && !contentTypePredicate.evaluate(contentType)) { closeConnectionQuietly(); throw new InvalidContentTypeException(contentType, dataSpec); } // If we requested a range starting from a non-zero position and received a 200 rather than a // 206, then the server does not support partial requests. We'll need to manually skip to the // requested position. bytesToSkip = responseCode == 200 && dataSpec.position != 0 ? dataSpec.position : 0; // Determine the length of the data to be read, after skipping. long contentLength = response.body().contentLength(); bytesToRead = dataSpec.length != C.LENGTH_UNBOUNDED ? dataSpec.length : contentLength != -1 ? contentLength - bytesToSkip : C.LENGTH_UNBOUNDED; opened = true; if (listener != null) { listener.onTransferStart(); } return bytesToRead; }
public void run() throws Exception { Request request = new Request.Builder().url("https://api.github.com/gists/c2a7c39532239ff261be").build(); Response response = client.newCall(request).execute(); if (!response.isSuccessful()) throw new IOException("Unexpected code " + response); Gist gist = gistJsonAdapter.fromJson(response.body().source()); response.body().close(); for (Map.Entry<String, GistFile> entry : gist.files.entrySet()) { System.out.println(entry.getKey()); System.out.println(entry.getValue().content); } }
public void isPackagerRunning(final PackagerStatusCallback callback) { String statusURL = createPackagerStatusURL(getDebugServerHost()); Request request = new Request.Builder().url(statusURL).build(); mClient .newCall(request) .enqueue( new Callback() { @Override public void onFailure(Call call, IOException e) { FLog.w( ReactConstants.TAG, "The packager does not seem to be running as we got an IOException requesting " + "its status: " + e.getMessage()); callback.onPackagerStatusFetched(false); } @Override public void onResponse(Call call, Response response) throws IOException { if (!response.isSuccessful()) { FLog.e( ReactConstants.TAG, "Got non-success http code from packager when requesting status: " + response.code()); callback.onPackagerStatusFetched(false); return; } ResponseBody body = response.body(); if (body == null) { FLog.e( ReactConstants.TAG, "Got null body response from packager when requesting status"); callback.onPackagerStatusFetched(false); return; } if (!PACKAGER_OK_STATUS.equals(body.string())) { FLog.e( ReactConstants.TAG, "Got unexpected response from packager when requesting status: " + body.string()); callback.onPackagerStatusFetched(false); return; } callback.onPackagerStatusFetched(true); } }); }
@Test public void checkRemoteDNSResolve() throws Exception { // This testcase will fail if the target is resolved locally instead of through the proxy. server.enqueue(new MockResponse().setBody("abc")); OkHttpClient client = new OkHttpClient.Builder().setProxy(socksProxy.proxy()).build(); HttpUrl url = server.url("/").newBuilder().host(socksProxy.HOSTNAME_THAT_ONLY_THE_PROXY_KNOWS).build(); Request request = new Request.Builder().url(url).build(); Response response1 = client.newCall(request).execute(); assertEquals("abc", response1.body().string()); assertEquals(1, socksProxy.connectionCount()); }
/** * post请求 * * @param tag * @param url * @param headers * @param params * @param postCallBack */ public static void post( Object tag, String url, Map<String, String> headers, Map<String, String> params, final PostCallBack postCallBack) { Logger.i(TAG, "post url :" + url); setCancel(false); RequestBody requestBody = null; FormBody.Builder formBodyBuilder = new FormBody.Builder(); if (params == null || params.size() == 0) { requestBody = formBodyBuilder.build(); } else { for (Map.Entry<String, String> me : params.entrySet()) { formBodyBuilder.add(me.getKey(), me.getValue()); } requestBody = formBodyBuilder.build(); } Request.Builder requestBuilder = new Request.Builder(); requestBuilder.tag(tag); requestBuilder.url(url); appendHeaders(requestBuilder, headers); requestBuilder.post(requestBody); Request request = requestBuilder.build(); mCall = mClient.newCall(request); mCalls.add(mCall); mCall.enqueue( new Callback() { @Override public void onFailure(Call call, IOException e) { Logger.e(TAG, "post onFailure :" + e.toString()); postCallBack.onFailure(call, e); EventBus.getDefault().post(new NetWorkBadEvent()); } @Override public void onResponse(Call call, Response response) throws IOException { if (response.isSuccessful()) { Logger.i(TAG, "post onResponse"); postCallBack.onResponse(call, response); } else { Logger.i(TAG, "post onError: " + response.code()); postCallBack.onError(response.code()); } } }); }
/** * post JSON data to server * * @param url * @param json * @param callBack */ public void post(String url, String json, final HttpCallBack callBack) { RequestBody body = RequestBody.create(MEDIA_TYPE_JSON, json); Request request = new Request.Builder().url(url).post(body).build(); Response response = null; try { response = mOkHttpClient.newCall(request).execute(); if (response.isSuccessful()) { callBack.onSuccess(response.body().string()); } else { callBack.onError(new Exception("Unexpected code " + response)); } } catch (IOException e) { e.printStackTrace(); callBack.onError(e); } }
protected JSONObject doInBackground(String... strings) { JSONObject jsonObject = null; OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder().url(URL_JSON).build(); Response response; try { response = client.newCall(request).execute(); if (!response.isSuccessful()) throw new IOException(String.valueOf(response)); jsonObject = new JSONObject(response.body().string()); } catch (IOException | JSONException e) { e.printStackTrace(); } return jsonObject; }
private < RequestType extends ConversationsDisplayRequest, ResponseType extends ConversationsDisplayResponse> LoadCallDisplay<RequestType, ResponseType> createCall( Class<ResponseType> responseTypeClass, RequestType request) { String fullUrl = String.format( "%s%s?%s", conversationsBaseUrl, request.getEndPoint(), request.getUrlQueryString()); Logger.d("url", fullUrl); Request okRequest = new Request.Builder() .addHeader("User-Agent", BVSDK.getInstance().getBvsdkUserAgent()) .url(fullUrl) .build(); return new LoadCallDisplay<RequestType, ResponseType>( request, responseTypeClass, okHttpClient.newCall(okRequest)); }
public Request getNaverMovie( Context context, String keyword, int start, int display, final OnResultListener<NaverMovies> listener) throws UnsupportedEncodingException { String url = String.format(URL_FORMAT, URLEncoder.encode(keyword, "utf-8"), start, display); final CallbackObject<NaverMovies> callbackObject = new CallbackObject<NaverMovies>(); Request request = new Request.Builder() .url(url) .header("X-Naver-Client-Id", "FRzO_6MMu6zwQYAaXlZr") .header("X-Naver-Client-Secret", "z0iOB55iQk") .tag(context) .build(); callbackObject.request = request; callbackObject.listener = listener; mClient .newCall(request) .enqueue( new Callback() { @Override public void onFailure(Call call, IOException e) { callbackObject.exception = e; Message msg = mHandler.obtainMessage(MESSAGE_FAILURE, callbackObject); mHandler.sendMessage(msg); } @Override public void onResponse(Call call, Response response) throws IOException { XMLParser parser = new XMLParser(); NaverMovies movies = parser.fromXml(response.body().byteStream(), "channel", NaverMovies.class); callbackObject.result = movies; Message msg = mHandler.obtainMessage(MESSAGE_SUCCESS, callbackObject); mHandler.sendMessage(msg); } }); return request; }
public String get(String url) { Request request = null; Response response = null; try { request = new Request.Builder().url(url).build(); response = client.newCall(request).execute(); if (response.isSuccessful()) { return response.body().string(); } return null; } catch (Exception e) { System.err.println(e); } finally { if (response != null && response.body() != null) { response.body().close(); } } return null; }
public void launchJSDevtools() { Request request = new Request.Builder().url(createLaunchJSDevtoolsCommandUrl()).build(); mClient .newCall(request) .enqueue( new Callback() { @Override public void onFailure(Call call, IOException e) { // ignore HTTP call response, this is just to open a debugger page and there is no // reason // to report failures from here } @Override public void onResponse(Call call, Response response) throws IOException { // ignore HTTP call response - see above } }); }
/** * 文件上传 * * @param tag * @param url * @param filePath * @param headers * @param params * @param uploadFileCallBack */ public static void uploadFile( Object tag, String url, String filePath, Map<String, String> headers, Map<String, String> params, final UploadFileCallBack uploadFileCallBack) { Logger.i(TAG, "uploadFile url :" + url); setCancel(false); File file = new File(filePath); MultipartBody.Builder multipartBuilder = new MultipartBody.Builder().setType(MultipartBody.FORM); addParams(multipartBuilder, params); addFiles(multipartBuilder, new Pair<String, File>("file", file)); progerssRequestBody = new ProgressRequestBody(multipartBuilder.build(), uploadFileCallBack); Request.Builder builder = new Request.Builder(); appendHeaders(builder, headers); Request request = builder.tag(tag).url(url).post(progerssRequestBody).build(); mCall = mClient.newCall(request); mCalls.add(mCall); mCall.enqueue( new Callback() { @Override public void onFailure(Call call, IOException e) { Logger.e(TAG, "uploadFile onFailure :" + e.toString()); uploadFileCallBack.onFailure(call, e); EventBus.getDefault().post(new NetWorkBadEvent()); } @Override public void onResponse(Call call, Response response) throws IOException { if (response.isSuccessful()) { Logger.i(TAG, "uploadFile onResponse"); uploadFileCallBack.onResponse(call, response); } else { Logger.i(TAG, "uploadFile onError: " + response.code()); uploadFileCallBack.onError(response.code()); } } }); }
static < RequestType extends ConversationsSubmissionRequest, ResponseType extends ConversationsResponse> LoadCallSubmission<RequestType, ResponseType> loadCallFromSubmission( Class<ResponseType> responseTypeClass, RequestType submission) { String fullUrl = String.format("%s%s", conversationsBaseUrl, submission.getEndPoint()); Log.d("url", fullUrl); String json = submission.getUrlQueryString(); RequestBody body = RequestBody.create(URL_ENCODED, json); Request okRequest = new Request.Builder() .post(body) .addHeader("Content-type", "application/x-www-form-urlencoded") .addHeader("User-Agent", BVSDK.getInstance().getBvsdkUserAgent()) .url(fullUrl) .build(); return new LoadCallSubmission<RequestType, ResponseType>( submission, responseTypeClass, okHttpClient.newCall(okRequest)); }
public void run() { OkHttpClient client = new OkHttpClient(); System.out.println("[PARAMS] : " + _token + " login -> " + _login); HttpUrl url = new HttpUrl.Builder() .scheme("https") .host("epitech-api.herokuapp.com") .addPathSegment("user") .addQueryParameter("token", _token) .addQueryParameter("user", _login) .build(); Request request = new Request.Builder().url(url).get().build(); try { infos = client.newCall(request).execute().body().string(); System.out.println("[RUN] : " + infos); } catch (IOException e) { e.printStackTrace(); } return; }
@Override public byte[] download(String url, String accepts) { HttpUrl httpUrl = HttpUrl.parse(url); if (httpUrl == null) { App.log.log(Level.SEVERE, "Invalid external resource URL", url); return null; } String host = httpUrl.host(); if (host == null) { App.log.log(Level.SEVERE, "External resource URL doesn't specify a host name", url); return null; } OkHttpClient resourceClient = HttpClient.create(); // authenticate only against a certain host, and only upon request resourceClient = HttpClient.addAuthentication( resourceClient, baseUrl.host(), settings.username(), settings.password()); // allow redirects resourceClient = resourceClient.newBuilder().followRedirects(true).build(); try { Response response = resourceClient.newCall(new Request.Builder().get().url(httpUrl).build()).execute(); ResponseBody body = response.body(); if (body != null) { @Cleanup InputStream stream = body.byteStream(); if (response.isSuccessful() && stream != null) { return IOUtils.toByteArray(stream); } else App.log.severe("Couldn't download external resource"); } } catch (IOException e) { App.log.log(Level.SEVERE, "Couldn't download external resource", e); } return null; }