Java Code Examples for org.apache.http.message.BasicHttpResponse#setEntity()
The following examples show how to use
org.apache.http.message.BasicHttpResponse#setEntity() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: HttpClientRequestExecutorTest.java From esigate with Apache License 2.0 | 6 votes |
private HttpResponse createMockGzippedResponse(String content) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); GZIPOutputStream gzos = new GZIPOutputStream(baos); byte[] uncompressedBytes = content.getBytes(); gzos.write(uncompressedBytes, 0, uncompressedBytes.length); gzos.close(); byte[] compressedBytes = baos.toByteArray(); ByteArrayEntity httpEntity = new ByteArrayEntity(compressedBytes); httpEntity.setContentType("text/html; charset=ISO-8859-1"); httpEntity.setContentEncoding("gzip"); StatusLine statusLine = new BasicStatusLine(new ProtocolVersion("p", 1, 2), HttpStatus.SC_OK, "OK"); BasicHttpResponse httpResponse = new BasicHttpResponse(statusLine); httpResponse.addHeader("Content-type", "text/html; charset=ISO-8859-1"); httpResponse.addHeader("Content-encoding", "gzip"); httpResponse.setEntity(httpEntity); return httpResponse; }
Example 2
Source File: DefaultsTest.java From data-prep with Apache License 2.0 | 6 votes |
@Test public void shouldPipeInputStream_handleIOError() throws Exception { // When final BasicHttpResponse response = buildResponse(); response.setEntity(new StringEntity("") { @Override public InputStream getContent() throws IOException { throw new IOException("Unexpected exception"); } }); try { Defaults.pipeStream().apply(buildRequest(), response); } catch (TDPException e) { // Then assertEquals(CommonErrorCodes.UNEXPECTED_EXCEPTION, e.getCode()); } }
Example 3
Source File: DefaultsTest.java From data-prep with Apache License 2.0 | 6 votes |
@Test public void shouldReadJsonResponse_ioException() throws Exception { // Given final ObjectMapper mapper = new ObjectMapper(); final BasicHttpResponse httpResponse = buildResponse(); httpResponse.setEntity(new StringEntity("") { @Override public InputStream getContent() throws IOException { throw new IOException(); } }); // When try { Defaults.convertResponse(mapper, Response.class).apply(buildRequest(), httpResponse); } catch (TDPException e) { // Then assertEquals(CommonErrorCodes.UNEXPECTED_EXCEPTION, e.getCode()); } }
Example 4
Source File: BasicNetworkTest.java From product-emm with Apache License 2.0 | 5 votes |
@Test public void headersAndPostParams() throws Exception { MockHttpStack mockHttpStack = new MockHttpStack(); BasicHttpResponse fakeResponse = new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 1), 200, "OK"); fakeResponse.setEntity(new StringEntity("foobar")); mockHttpStack.setResponseToReturn(fakeResponse); BasicNetwork httpNetwork = new BasicNetwork(mockHttpStack); Request<String> request = buildRequest(); httpNetwork.performRequest(request); assertEquals("foo", mockHttpStack.getLastHeaders().get("requestheader")); assertEquals("requestpost=foo&", new String(mockHttpStack.getLastPostBody())); }
Example 5
Source File: ClientExecutionAndRequestTimerTestUtils.java From ibm-cos-sdk-java with Apache License 2.0 | 5 votes |
private static HttpResponseProxy createHttpResponseProxy(HttpEntity entity) { ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1); BasicStatusLine statusLine = new BasicStatusLine(protocolVersion, 200, "mock response"); BasicHttpResponse response = new BasicHttpResponse(statusLine); response.setEntity(entity); return new HttpResponseProxy(response); }
Example 6
Source File: AmazonHttpClientTest.java From ibm-cos-sdk-java with Apache License 2.0 | 5 votes |
private BasicHttpResponse createBasicHttpResponse() { BasicHttpEntity entity = new BasicHttpEntity(); entity.setContent(new ByteArrayInputStream(new byte[0])); BasicHttpResponse response = new BasicHttpResponse( new ProtocolVersion("http", 1, 1), 200, "OK"); response.setEntity(entity); return response; }
Example 7
Source File: SlackNotificationTest.java From tcSlackBuildNotifier with MIT License | 5 votes |
@Test public void post_whenResponseIsOk_doesNotThrow() throws IOException { ArgumentCaptor<HttpPost> requestCaptor = ArgumentCaptor.forClass(HttpPost.class); HttpClient httpClient = mock(HttpClient.class); BasicHttpResponse response = new BasicHttpResponse(new BasicStatusLine(new ProtocolVersion("http", 1, 1), 200, "")); PostMessageResponse successfulResponse = new PostMessageResponse(); successfulResponse.setOk(true); successfulResponse.setError("channel_not_found"); response.setEntity(new StringEntity(successfulResponse.toJson())); when(httpClient.execute(requestCaptor.capture())).thenReturn(response); SlackNotification w = factory.getSlackNotification(httpClient, "#test-channel"); SlackNotificationPayloadContent content = new SlackNotificationPayloadContent(); content.setBuildDescriptionWithLinkSyntax("http://foo"); content.setCommits(new ArrayList<Commit>()); w.setPayload(content); w.setEnabled(true); w.post(); List<HttpPost> capturedRequests = requestCaptor.getAllValues(); HttpPost request = capturedRequests.get(0); assertNotNull(w.getResponse()); assertTrue(w.getResponse().getOk()); }
Example 8
Source File: HurlStack.java From android_tv_metro with Apache License 2.0 | 5 votes |
@Override public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders) throws IOException, AuthFailureError { String url = request.getUrl(); HashMap<String, String> map = new HashMap<String, String>(); map.putAll(request.getHeaders()); map.putAll(additionalHeaders); if (mUrlRewriter != null) { String rewritten = mUrlRewriter.rewriteUrl(url); if (rewritten == null) { throw new IOException("URL blocked by rewriter: " + url); } url = rewritten; } URL parsedUrl = new URL(url); HttpURLConnection connection = openConnection(parsedUrl, request); for (String headerName : map.keySet()) { connection.addRequestProperty(headerName, map.get(headerName)); } setConnectionParametersForRequest(connection, request); // Initialize HttpResponse with data from the HttpURLConnection. ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1); int responseCode = connection.getResponseCode(); if (responseCode == -1) { // -1 is returned by getResponseCode() if the response code could not be retrieved. // Signal to the caller that something was wrong with the connection. throw new IOException("Could not retrieve response code from HttpUrlConnection."); } StatusLine responseStatus = new BasicStatusLine(protocolVersion, connection.getResponseCode(), connection.getResponseMessage()); BasicHttpResponse response = new BasicHttpResponse(responseStatus); response.setEntity(entityFromConnection(connection)); for (Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) { if (header.getKey() != null) { Header h = new BasicHeader(header.getKey(), header.getValue().get(0)); response.addHeader(h); } } return response; }
Example 9
Source File: ElasticsearchBackendImplTest.java From fiware-cygnus with GNU Affero General Public License v3.0 | 5 votes |
/** * setup test case * * @throws Exception */ @Before public void setUp() throws Exception { BasicHttpResponse response = new BasicHttpResponse(new ProtocolVersion("http", 1, 1), statusCode, "Internal Server Error"); response.setEntity(new StringEntity("{\"result\": {\"whatever\":\"whatever\"}}")); MockitoAnnotations.initMocks(this); when(mockHttpClient.execute(Mockito.any(HttpPost.class))).thenReturn(response); }
Example 10
Source File: SlackNotificationListenerTest.java From tcSlackBuildNotifier with MIT License | 5 votes |
@Before public void setUp() throws Exception { HttpClient httpClient = mock(HttpClient.class); BasicHttpResponse response = new BasicHttpResponse(new BasicStatusLine(new ProtocolVersion("http", 1, 1), 200, "")); PostMessageResponse successfulResponse = new PostMessageResponse(); successfulResponse.setOk(true); successfulResponse.setError("channel_not_found"); response.setEntity(new StringEntity(successfulResponse.toJson())); when(httpClient.execute(isA(HttpUriRequest.class))).thenReturn(response); slackNotificationImpl = new SlackNotificationImpl(httpClient, ""); spySlackNotification = spy(slackNotificationImpl); whl = new SlackNotificationListener(sBuildServer, settings, configSettings, manager, factory); projSettings = new SlackNotificationProjectSettings(); when(factory.getSlackNotification()).thenReturn(spySlackNotification); //when(manager.isRegisteredFormat("JSON")).thenReturn(true); // when(manager.getFormat("JSON")).thenReturn(payload); //when(manager.getServer()).thenReturn(sBuildServer); when(sBuildServer.getProjectManager()).thenReturn(projectManager); when(projectManager.findProjectById("project1")).thenReturn(sProject); when(sBuildServer.getHistory()).thenReturn(buildHistory); when(sBuildServer.getRootUrl()).thenReturn("http://test.server"); when(previousSuccessfulBuild.getBuildStatus()).thenReturn(Status.NORMAL); when(previousSuccessfulBuild.isPersonal()).thenReturn(false); when(previousFailedBuild.getBuildStatus()).thenReturn(Status.FAILURE); when(previousFailedBuild.isPersonal()).thenReturn(false); finishedSuccessfulBuilds.add(previousSuccessfulBuild); finishedFailedBuilds.add(previousFailedBuild); sBuildType.setProject(sProject); when(settings.getSettings(sRunningBuild.getProjectId(), "slackNotifications")).thenReturn(projSettings); whl.register(); }
Example 11
Source File: BasicNetworkTest.java From SaveVolley with Apache License 2.0 | 5 votes |
@Test public void headersAndPostParams() throws Exception { MockHttpStack mockHttpStack = new MockHttpStack(); BasicHttpResponse fakeResponse = new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 1), 200, "OK"); fakeResponse.setEntity(new StringEntity("foobar")); mockHttpStack.setResponseToReturn(fakeResponse); BasicNetwork httpNetwork = new BasicNetwork(mockHttpStack); Request<String> request = buildRequest(); httpNetwork.performRequest(request); assertEquals("foo", mockHttpStack.getLastHeaders().get("requestheader")); assertEquals("requestpost=foo&", new String(mockHttpStack.getLastPostBody())); }
Example 12
Source File: OkHttp3Stack.java From QuickLyric with GNU General Public License v3.0 | 5 votes |
@Override public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders) throws IOException, AuthFailureError { // OkHttpClient.Builder clientBuilder = client.newBuilder(); // int timeoutMs = request.getTimeoutMs(); // clientBuilder.connectTimeout(timeoutMs, TimeUnit.MILLISECONDS); // clientBuilder.readTimeout(timeoutMs, TimeUnit.MILLISECONDS); // clientBuilder.writeTimeout(timeoutMs, TimeUnit.MILLISECONDS); // OkHttpClient client = clientBuilder.build(); okhttp3.Request.Builder requestBuilder = new okhttp3.Request.Builder(); requestBuilder.url(request.getUrl()); setHeaders(requestBuilder, request, additionalHeaders); setConnectionParameters(requestBuilder, request); okhttp3.Request okHttpRequest = requestBuilder.build(); Call okHttpCall = client.newCall(okHttpRequest); Response okHttpResponse = okHttpCall.execute(); StatusLine responseStatus = new BasicStatusLine(parseProtocol(okHttpResponse.protocol()), okHttpResponse.code(), okHttpResponse.message()); BasicHttpResponse response = new BasicHttpResponse(responseStatus); response.setEntity(getEntity(okHttpResponse)); Headers responseHeaders = okHttpResponse.headers(); for (int i = 0, len = responseHeaders.size(); i < len; i++) { response.addHeader(new BasicHeader(responseHeaders.name(i), responseHeaders.value(i))); } return response; }
Example 13
Source File: HurlStack.java From SaveVolley with Apache License 2.0 | 4 votes |
@Override public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders) throws IOException, AuthFailureError { // 获取 Volley 抽象请求 Request 中的 String 类型的 Url String url = request.getUrl(); // 实例化一个 HashMap 来存放 Header 信息 HashMap<String, String> map = new HashMap<String, String>(); map.putAll(request.getHeaders()); map.putAll(additionalHeaders); // 判断是否有 Url 重写的逻辑 if (mUrlRewriter != null) { String rewritten = mUrlRewriter.rewriteUrl(url); if (rewritten == null) { throw new IOException("URL blocked by rewriter: " + url); } // 重新赋值上 UrlRewriter 接口 重写的 Url url = rewritten; } // 实例化一个 java.net.Url 对象 URL parsedUrl = new URL(url); /* * 将 URL 对象 和 Volley 的抽象请求 Request 传入到 openConnection(...) 方法内 * 完成 Volley 抽象请求 Request -> HttpURLConnection 的转换过渡 * 此时拿到一个 HttpURLConnection 对象 */ HttpURLConnection connection = openConnection(parsedUrl, request); // 根据刚才存放 Header 信息的 Map,给 HttpURLConnection 添加头信息 for (String headerName : map.keySet()) { connection.addRequestProperty(headerName, map.get(headerName)); } // 设置 HttpURLConnection 请求方法类型 setConnectionParametersForRequest(connection, request); // Initialize HttpResponse with data from the HttpURLConnection. /* * 初始化 一个 Apache 的 HTTP 协议 ( ProtocolVersion ) */ ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1); /* * 正常情况下 HttpURLConnection 是依靠 connect() 发请求的 * * 但是 HttpURLConnection 的 getInputStream() 和 getOutputStream() 也会自动调用 connect() * * HttpURLConnection 的 getResponseCode() 会调用 getInputStream() * 然后 getInputStream() 又会自动调用 connect(),于是 * * 这里就是 发请求了 */ int responseCode = connection.getResponseCode(); // responseCode == -1 表示 没有返回内容 if (responseCode == -1) { // -1 is returned by getResponseCode() if the response code could not be retrieved. // Signal to the caller that something was wrong with the connection. throw new IOException("Could not retrieve response code from HttpUrlConnection."); } // 实例化 org.apache.http.StatusLine 对象 StatusLine responseStatus = new BasicStatusLine(protocolVersion, connection.getResponseCode(), connection.getResponseMessage()); // 用 org.apache.http.StatusLine 去实例化一个 Apache 的 Response BasicHttpResponse response = new BasicHttpResponse(responseStatus); /* * 判断请求结果 Response 是否存在 body * * 有的话,给刚才实例话的 Apache Response 设置 HttpEntity( 调用 entityFromConnection(...) * 通过一个 HttpURLConnection 获取其对应的 HttpEntity ) */ if (hasResponseBody(request.getMethod(), responseStatus.getStatusCode())) { response.setEntity(entityFromConnection(connection)); } // 设置 请求结果 Response 的头信息 for (Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) { if (header.getKey() != null) { Header h = new BasicHeader(header.getKey(), header.getValue().get(0)); response.addHeader(h); } } // 返回设置好的 Apache Response return response; }
Example 14
Source File: HurlStack.java From product-emm with Apache License 2.0 | 4 votes |
@Override public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders) throws IOException, AuthFailureError { String url = request.getUrl(); HashMap<String, String> map = new HashMap<String, String>(); map.putAll(request.getHeaders()); map.putAll(additionalHeaders); if (mUrlRewriter != null) { String rewritten = mUrlRewriter.rewriteUrl(url); if (rewritten == null) { throw new IOException("URL blocked by rewriter: " + url); } url = rewritten; } URL parsedUrl = new URL(url); HttpURLConnection connection = openConnection(parsedUrl, request); for (String headerName : map.keySet()) { connection.addRequestProperty(headerName, map.get(headerName)); } setConnectionParametersForRequest(connection, request); // Initialize HttpResponse with data from the HttpURLConnection. ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1); int responseCode = connection.getResponseCode(); if (responseCode == -1) { // -1 is returned by getResponseCode() if the response code could not be retrieved. // Signal to the caller that something was wrong with the connection. throw new IOException("Could not retrieve response code from HttpUrlConnection."); } StatusLine responseStatus = new BasicStatusLine(protocolVersion, connection.getResponseCode(), connection.getResponseMessage()); BasicHttpResponse response = new BasicHttpResponse(responseStatus); if (hasResponseBody(request.getMethod(), responseStatus.getStatusCode())) { response.setEntity(entityFromConnection(connection)); } for (Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) { if (header.getKey() != null) { Header h = new BasicHeader(header.getKey(), header.getValue().get(0)); response.addHeader(h); } } return response; }
Example 15
Source File: HurlStack.java From volley_demo with Apache License 2.0 | 4 votes |
@Override public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders) throws IOException, AuthFailureError { String url = request.getUrl(); HashMap<String, String> map = new HashMap<String, String>(); map.putAll(request.getHeaders()); map.putAll(additionalHeaders); if (mUrlRewriter != null) { String rewritten = mUrlRewriter.rewriteUrl(url); if (rewritten == null) { throw new IOException("URL blocked by rewriter: " + url); } url = rewritten; } URL parsedUrl = new URL(url); HttpURLConnection connection = openConnection(parsedUrl, request); for (String headerName : map.keySet()) { connection.addRequestProperty(headerName, map.get(headerName)); } setConnectionParametersForRequest(connection, request); // Initialize HttpResponse with data from the HttpURLConnection. ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1); int responseCode = connection.getResponseCode(); if (responseCode == -1) { // -1 is returned by getResponseCode() if the response code could not be retrieved. // Signal to the caller that something was wrong with the connection. throw new IOException("Could not retrieve response code from HttpUrlConnection."); } StatusLine responseStatus = new BasicStatusLine(protocolVersion, connection.getResponseCode(), connection.getResponseMessage()); BasicHttpResponse response = new BasicHttpResponse(responseStatus); if (hasResponseBody(request.getMethod(), responseStatus.getStatusCode())) { response.setEntity(entityFromConnection(connection)); } for (Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) { if (header.getKey() != null) { Header h = new BasicHeader(header.getKey(), header.getValue().get(0)); response.addHeader(h); } } return response; }
Example 16
Source File: HurlStack.java From volley with Apache License 2.0 | 4 votes |
@Override public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders) throws IOException, AuthFailureError { String url = request.getUrl(); HashMap<String, String> map = new HashMap<String, String>(); // chenbo add gzip support,new user-agent if (request.isShouldGzip()) { map.put(HEADER_ACCEPT_ENCODING, ENCODING_GZIP); } map.put(USER_AGENT, mUserAgent); // end map.putAll(request.getHeaders()); map.putAll(additionalHeaders); if (mUrlRewriter != null) { String rewritten = mUrlRewriter.rewriteUrl(url); if (rewritten == null) { throw new IOException("URL blocked by rewriter: " + url); } url = rewritten; } URL parsedUrl = new URL(url); HttpURLConnection connection = openConnection(parsedUrl, request); for (String headerName : map.keySet()) { connection.addRequestProperty(headerName, map.get(headerName)); } // if (request instanceof MultiPartRequest) { // setConnectionParametersForMultipartRequest(connection, request); // } else { // } setConnectionParametersForRequest(connection, request); // Initialize HttpResponse with data from the HttpURLConnection. ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1); int responseCode = connection.getResponseCode(); if (responseCode == -1) { // -1 is returned by getResponseCode() if the response code could not be retrieved. // Signal to the caller that something was wrong with the connection. throw new IOException("Could not retrieve response code from HttpUrlConnection."); } StatusLine responseStatus = new BasicStatusLine(protocolVersion, connection.getResponseCode(), connection.getResponseMessage()); BasicHttpResponse response = new BasicHttpResponse(responseStatus); response.setEntity(entityFromConnection(connection)); for (Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) { if (header.getKey() != null) { if (header.getKey() != null) { String value = ""; for(String head : header.getValue()){ value += head + ";"; } if(value.length() > 0) { value = value.substring(0,value.length() - 1); } Header h = new BasicHeader(header.getKey(), value); response.addHeader(h); } } } if (ENCODING_GZIP.equalsIgnoreCase(connection.getContentEncoding())) { response.setEntity(new InflatingEntity(response.getEntity())); } return response; }
Example 17
Source File: OkHttpStack.java From something.apk with MIT License | 4 votes |
@Override public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders) throws IOException, AuthFailureError { String url = request.getUrl(); HashMap<String, String> map = new HashMap<String, String>(); map.putAll(request.getHeaders()); map.putAll(additionalHeaders); if (mUrlRewriter != null) { String rewritten = mUrlRewriter.rewriteUrl(url); if (rewritten == null) { throw new IOException("URL blocked by rewriter: " + url); } url = rewritten; } URL parsedUrl = new URL(url); HttpURLConnection connection = openConnection(parsedUrl, request); for (String headerName : map.keySet()) { connection.addRequestProperty(headerName, map.get(headerName)); } setConnectionParametersForRequest(connection, request); // Initialize HttpResponse with data from the HttpURLConnection. ProtocolVersion protocolVersion = new ProtocolVersion("HTTPS", 1, 1); int responseCode = connection.getResponseCode(); if (responseCode == -1) { // -1 is returned by getResponseCode() if the response code could not be retrieved. // Signal to the caller that something was wrong with the connection. throw new IOException("Could not retrieve response code from HttpUrlConnection."); } StatusLine responseStatus = new BasicStatusLine(protocolVersion, connection.getResponseCode(), connection.getResponseMessage()); BasicHttpResponse response = new BasicHttpResponse(responseStatus); response.setEntity(entityFromConnection(connection)); for (Map.Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) { if (header.getKey() != null) { Header h = new BasicHeader(header.getKey(), header.getValue().get(0)); response.addHeader(h); } } URL finalUrl = connection.getURL(); if(!parsedUrl.equals(finalUrl) && request instanceof Redirectable){ ((Redirectable) request).onRedirect(finalUrl.toExternalForm()); } return response; }
Example 18
Source File: HurlStack.java From CrossBow with Apache License 2.0 | 4 votes |
@Override public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders) throws IOException, AuthFailureError { String url = request.getUrl(); HashMap<String, String> map = new HashMap<String, String>(); map.putAll(request.getHeaders()); map.putAll(additionalHeaders); if (mUrlRewriter != null) { String rewritten = mUrlRewriter.rewriteUrl(url); if (rewritten == null) { throw new IOException("URL blocked by rewriter: " + url); } url = rewritten; } URL parsedUrl = new URL(url); HttpURLConnection connection = openConnection(parsedUrl, request); for (String headerName : map.keySet()) { connection.addRequestProperty(headerName, map.get(headerName)); } setConnectionParametersForRequest(connection, request); // Initialize HttpResponse with data from the HttpURLConnection. ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1); int responseCode = connection.getResponseCode(); if (responseCode == -1) { // -1 is returned by getResponseCode() if the response code could not be retrieved. // Signal to the caller that something was wrong with the connection. throw new IOException("Could not retrieve response code from HttpUrlConnection."); } StatusLine responseStatus = new BasicStatusLine(protocolVersion, connection.getResponseCode(), connection.getResponseMessage()); BasicHttpResponse response = new BasicHttpResponse(responseStatus); if (hasResponseBody(request.getMethod(), responseStatus.getStatusCode())) { response.setEntity(entityFromConnection(connection)); } for (Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) { if (header.getKey() != null) { Header h = new BasicHeader(header.getKey(), header.getValue().get(0)); response.addHeader(h); } } return response; }
Example 19
Source File: OkHttpURLConnectionStack.java From AndroidProjects with MIT License | 4 votes |
@Override public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders) throws IOException, AuthFailureError { int timeoutMs = request.getTimeoutMs(); OkHttpClient client = mClient.newBuilder() .connectTimeout(timeoutMs, TimeUnit.MILLISECONDS) .readTimeout(timeoutMs, TimeUnit.MILLISECONDS) .writeTimeout(timeoutMs, TimeUnit.MILLISECONDS).build(); HashMap<String, String> map = new HashMap<String, String>(); map.putAll(request.getHeaders()); map.putAll(additionalHeaders); okhttp3.Request.Builder okHttpRequestBuilder = new okhttp3.Request.Builder(); for (String headerName : map.keySet()) { okHttpRequestBuilder.addHeader(headerName, map.get(headerName)); } for (final String name : additionalHeaders.keySet()) { okHttpRequestBuilder.addHeader(name, additionalHeaders.get(name)); } setConnectionParametersForRequest(okHttpRequestBuilder, request); okhttp3.Request okHttpRequest = okHttpRequestBuilder.url(request.getUrl()).build(); Call okHttpCall = client.newCall(okHttpRequest); Response okHttpResponse = okHttpCall.execute(); StatusLine responseStatus = new BasicStatusLine( parseProtocol(okHttpResponse.protocol()), okHttpResponse.code(), okHttpResponse.message()); BasicHttpResponse response = new BasicHttpResponse(responseStatus); response.setEntity(entityFromOkHttpResponse(okHttpResponse)); Headers responseHeaders = okHttpResponse.headers(); for (int i = 0, len = responseHeaders.size(); i < len; i++) { final String name = responseHeaders.name(i), value = responseHeaders.value(i); if (name != null) { response.addHeader(new BasicHeader(name, value)); } } return response; }
Example 20
Source File: DirectoryAdapter.java From emissary with Apache License 2.0 | 4 votes |
/** * Handle the packaging and sending of an addPlaces call to a remote directory. Sends multiple keys on the same place * with the same cost/quality and description if the description, cost and quality lists are only size 1. Uses a * distinct description/cost/quality for each key when there are enough values * * @param parentDirectory the url portion of the parent directory location * @param entryList the list of directory entries to add * @param propagating true if going downstream * @return status of operation */ public EmissaryResponse outboundAddPlaces(final String parentDirectory, final List<DirectoryEntry> entryList, final boolean propagating) { if (disableAddPlaces) { BasicHttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "Not accepting remote add places"); response.setEntity(EntityBuilder.create().setText("").setContentEncoding(MediaType.TEXT_PLAIN).build()); return new EmissaryResponse(response); } else { final String parentDirectoryUrl = KeyManipulator.getServiceHostURL(parentDirectory); final HttpPost method = new HttpPost(parentDirectoryUrl + CONTEXT + "/RegisterPlace.action"); final String parentLoc = KeyManipulator.getServiceLocation(parentDirectory); // Separate it out into lists final List<String> keyList = new ArrayList<String>(); final List<String> descList = new ArrayList<String>(); final List<Integer> costList = new ArrayList<Integer>(); final List<Integer> qualityList = new ArrayList<Integer>(); for (final DirectoryEntry d : entryList) { keyList.add(d.getKey()); descList.add(d.getDescription()); costList.add(Integer.valueOf(d.getCost())); qualityList.add(Integer.valueOf(d.getQuality())); } final List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair(TARGET_DIRECTORY, parentLoc)); for (int count = 0; count < keyList.size(); count++) { nvps.add(new BasicNameValuePair(ADD_KEY + count, keyList.get(count))); // possibly use the single desc/cost/qual for each key if (descList.size() > count) { String desc = descList.get(count); if (desc == null) { desc = "No description provided"; } nvps.add(new BasicNameValuePair(ADD_DESCRIPTION + count, desc)); } if (costList.size() > count) { nvps.add(new BasicNameValuePair(ADD_COST + count, costList.get(count).toString())); } if (qualityList.size() > count) { nvps.add(new BasicNameValuePair(ADD_QUALITY + count, qualityList.get(count).toString())); } } nvps.add(new BasicNameValuePair(ADD_PROPAGATION_FLAG, Boolean.toString(propagating))); method.setEntity(new UrlEncodedFormEntity(nvps, Charset.defaultCharset())); return send(method); } }