Mocking Apache HTTPClient using Mockito - java

I'm trying to mock Apache HttpClient Interface in order to mock one of its methods mentioned below to return a stubbed JSON object in response.
HttpResponse response = defaultHttpClient.execute(postRequest);
Could somebody be able to suggest how to achieve this with some sample code? Your help would be greatly appreciated.
Thanks

Here is what I did to test my code using Mockito and Apache HttpBuilder:
Class under test:
import java.io.BufferedReader;
import java.io.IOException;
import javax.ws.rs.core.Response.Status;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class StatusApiClient {
private static final Logger LOG = LoggerFactory.getLogger(StatusApiClient.class);
private String targetUrl = "";
private HttpClient client = null;
HttpGet httpGet = null;
public StatusApiClient(HttpClient client, HttpGet httpGet) {
this.client = client;
this.httpGet = httpGet;
}
public StatusApiClient(String targetUrl) {
this.targetUrl = targetUrl;
this.client = HttpClientBuilder.create().build();
this.httpGet = new HttpGet(targetUrl);
}
public boolean getStatus() {
BufferedReader rd = null;
boolean status = false;
try{
LOG.debug("Requesting status: " + targetUrl);
HttpResponse response = client.execute(httpGet);
if(response.getStatusLine().getStatusCode() == Status.OK.getStatusCode()) {
LOG.debug("Is online.");
status = true;
}
} catch(Exception e) {
LOG.error("Error getting the status", e);
} finally {
if (rd != null) {
try{
rd.close();
} catch (IOException ioe) {
LOG.error("Error while closing the Buffered Reader used for reading the status", ioe);
}
}
}
return status;
}
}
Test:
import java.io.IOException;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.HttpHostConnectException;
import org.junit.Assert;
import org.junit.Test;
import org.mockito.Mockito;
public class StatusApiClientTest extends Mockito {
#Test
public void should_return_true_if_the_status_api_works_properly() throws ClientProtocolException, IOException {
//given:
HttpClient httpClient = mock(HttpClient.class);
HttpGet httpGet = mock(HttpGet.class);
HttpResponse httpResponse = mock(HttpResponse.class);
StatusLine statusLine = mock(StatusLine.class);
//and:
when(statusLine.getStatusCode()).thenReturn(200);
when(httpResponse.getStatusLine()).thenReturn(statusLine);
when(httpClient.execute(httpGet)).thenReturn(httpResponse);
//and:
StatusApiClient client = new StatusApiClient(httpClient, httpGet);
//when:
boolean status = client.getStatus();
//then:
Assert.assertTrue(status);
}
#Test
public void should_return_false_if_status_api_do_not_respond() throws ClientProtocolException, IOException {
//given:
HttpClient httpClient = mock(HttpClient.class);
HttpGet httpGet = mock(HttpGet.class);
HttpResponse httpResponse = mock(HttpResponse.class);
StatusLine statusLine = mock(StatusLine.class);
//and:
when(httpClient.execute(httpGet)).thenThrow(HttpHostConnectException.class);
//and:
StatusApiClient client = new StatusApiClient(httpClient, httpGet);
//when:
boolean status = client.getStatus();
//then:
Assert.assertFalse(status);
}
}
What do you think folks, do I need to improve something? (Yeah, I know, the comments. That is something I brought from my Spock background :D)

In your unit test class you need to mock defaultHttpClient:
#Mock
private HttpClient defaultHttpClient;
Then you tell mockito (for example in #Before method) to actually create your mocks by:
MockitoAnnotations.initMocks(YourTestClass);
Then in your test method you define what execute() method should return:
when(defaultHttpClient.execute(any()/* or wahtever you want here */)).thenReturn(stubbed JSON object);

There is a nicer way to do this without having to add PowerMock as yet another dependency. Here you only need an extra constructor taking HTTPClient as an argument and Mockito. In this example I'm creating a custom health check (Spring Actuator) and I need to mock the HTTPClient for unit testing.
Libs: JUnit 5, Spring Boot 2.1.2 and Mockito 2.
Component:
#Component
public class MyHealthCheck extends AbstractHealthIndicator {
HttpClient httpClient;
public MyHealthCheck() {
httpClient = HttpClientBuilder.create().build();
}
/**
Added another constructor to the class with an HttpClient argument.
This one can be used for testing
*/
public MyHealthCheck(HttpClient httpClient) {
this.httpClient = httpClient;
}
/**
Method to test
*/
#Override
protected void doHealthCheck(Builder builder) throws Exception {
//
// Execute request and get status code
HttpGet request = new HttpGet("http://www.SomeAuthEndpoint.com");
HttpResponse response = httpClient.execute(request);
//
// Update builder according to status code
int statusCode = response.getStatusLine().getStatusCode();
if(statusCode == 200 || statusCode == 401) {
builder.up().withDetail("Code from service", statusCode);
} else {
builder.unknown().withDetail("Code from service", statusCode);
}
}
}
Test method:
Note that here we use Mockito.any(HttpGet.class)
private static HttpClient httpClient;
private static HttpResponse httpResponse;
private static StatusLine statusLine;
#BeforeAll
public static void init() {
//
// Given
httpClient = Mockito.mock(HttpClient.class);
httpResponse = Mockito.mock(HttpResponse.class);
statusLine = Mockito.mock(StatusLine.class);
}
#Test
public void doHealthCheck_endReturns401_shouldReturnUp() throws Exception {
//
// When
when(statusLine.getStatusCode()).thenReturn(401);
when(httpResponse.getStatusLine()).thenReturn(statusLine);
when(httpClient.execute(Mockito.any(HttpGet.class))).thenReturn(httpResponse);
//
// Then
MyHealthCheck myHealthCheck = new MyHealthCheck(httpClient);
Health.Builder builder = new Health.Builder();
myHealthCheck.doHealthCheck(builder);
Status status = builder.build().getStatus();
Assertions.assertTrue(Status.UP == status);
}

You can look at HttpClientMock, I wrote it for internal project but later decided to open source. It allows you to define mock behavior with fluent API and later verify a number of made calls. Example:
HttpClientMock httpClientMock = new
HttpClientMock("http://localhost:8080");
httpClientMock.onGet("/login?user=john").doReturnJSON("{permission:1}");
httpClientMock.verify().get("/login?user=john").called();

You can do this easily using PowerMockito which can also mock final/static methods, private methods and anonymous classes easily. Here's the sample code for mocking http request. JSON_STRING_DATA is any string which you want to get from execute method.
PowerMockito.mockStatic(DefaultHttpClient.class);
HttpClient defaultHttpClientMocked = PowerMockito.mock(DefaultHttpClient.class);
PowerMockito.when(defaultHttpClientMocked.execute(Mockito.any(HttpPost.class))).thenReturn(createMockedHTTPResponse(JSON_STRING_DATA));

Related

How to set up a multipart POST request in java 11?

I am trying to build a multipart HttpRequest using Java 11 as below. I am also trying to pass username
and password and later i might need a file also in the same request. However i keep getting 415 or 400 bad request errors.
The code is below.
import java.io.IOException;
import java.math.BigInteger;
import java.net.URI;
import java.net.URLEncoder;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.time.Duration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
public class Client{
private HttpClient httpClient;
private HttpResponse httpResponse;
private String Response;
private Map<Object, Object> urlParameters;
public Client(String URL) {
httpClient=BuildClient(URL);
urlParameters= new HashMap<>();
urlParameters.put("username","xxxx");
urlParameters.put("password","xxxx");
try {
PostRequest(httpClient,URL,urlParameters);
} catch (IOException e) {
System.out.println("Client Error");
e.printStackTrace();
}
}
public HttpClient BuildClient(String URL) {
return HttpClient.newBuilder()
.version(HttpClient.Version.HTTP_2)
.connectTimeout(Duration.ofSeconds(10))
.build();
}
//This is the code for request build
public HttpResponse PostRequest(HttpClient httpClient, String url, Map<Object, Object> params) throws IOException {
String boundary = new BigInteger(256, new Random()).toString();
HttpRequest request = HttpRequest.newBuilder()
//.POST(HttpRequest.BodyPublishers.fromPublisher(subscriber -> ))
.POST(HttpRequest.BodyPublishers.noBody())
.POST(HttpRequest.BodyPublishers.ofString("{\"username\":\"XXXXX\"}{\"password\":\"XXXX\"}"))
//.POST(HttpRequest.BodyPublishers.ofFile(Path.of("")))
.uri(URI.create("http://example.com/request/add"))
.setHeader("User-Agent", "firefox")
.setHeader("Content-Type", "multipart/form-data")
.build();
HttpResponse<String> response = null;
try {
response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(request.headers());
// print status code
System.out.println(response.statusCode());
// print response body
System.out.println(response.body());
return response;
}
public HttpRequest.BodyPublisher FormatData(Map<Object, Object> data) {
var builder = new StringBuilder();
for (Map.Entry<Object, Object> entry : data.entrySet()) {
if(builder.length()>0)
{
builder.append("&");
}
builder.append(URLEncoder.encode(entry.getKey().toString(), StandardCharsets.UTF_8));
builder.append("=");
builder.append(URLEncoder.encode(entry.getValue().toString(), StandardCharsets.UTF_8));
}
return HttpRequest.BodyPublishers.ofString(builder.toString());
//return null;
}
}
I was wandering if can be done without add some library as maven dependency such as apache HTTP client.

How to get httpclient response as stream

I am using httpclient 4.5.5
i want to get large files upto 1 gb in response. But it seems like
CloseableHttpResponse response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
This returns whole response so its not good to have whole response in memory. Is there any way to get response as stream?
Apache HttpClient as of version 4.0 (as well as Apache HttpAsyncClient) supports full content streaming for both incoming and outgoing HTTP messages. Use HttpEntity to get access to the underling content input stream
CloseableHttpClient client = HttpClients.createDefault();
HttpGet httpGet = new HttpGet("http://myhost/tons-of-stuff");
try (CloseableHttpResponse response1 = client.execute(httpGet)) {
final HttpEntity entity = response1.getEntity();
if (entity != null) {
try (InputStream inputStream = entity.getContent()) {
// do something useful with the stream
}
}
}
You need Apache Async Client.
HttpAsyncClient is the ASYNC version of Apache HttpClient. Apache HttpClient construct the whole response in memory, while with HttpAsyncClient, you can define a Handler (Consumer) to process the response while receiving data.
https://hc.apache.org/httpcomponents-asyncclient-4.1.x/index.html
Here is an example from their official example code
package org.apache.http.examples.nio.client;
import java.io.IOException;
import java.nio.CharBuffer;
import java.util.concurrent.Future;
import org.apache.http.HttpResponse;
import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
import org.apache.http.impl.nio.client.HttpAsyncClients;
import org.apache.http.nio.IOControl;
import org.apache.http.nio.client.methods.AsyncCharConsumer;
import org.apache.http.nio.client.methods.HttpAsyncMethods;
import org.apache.http.protocol.HttpContext;
/**
* This example demonstrates an asynchronous HTTP request / response exchange with
* a full content streaming.
*/
public class AsyncClientHttpExchangeStreaming {
public static void main(final String[] args) throws Exception {
CloseableHttpAsyncClient httpclient = HttpAsyncClients.createDefault();
try {
httpclient.start();
Future<Boolean> future = httpclient.execute(
HttpAsyncMethods.createGet("http://httpbin.org/"),
new MyResponseConsumer(), null);
Boolean result = future.get();
if (result != null && result.booleanValue()) {
System.out.println("Request successfully executed");
} else {
System.out.println("Request failed");
}
System.out.println("Shutting down");
} finally {
httpclient.close();
}
System.out.println("Done");
}
static class MyResponseConsumer extends AsyncCharConsumer<Boolean> {
#Override
protected void onResponseReceived(final HttpResponse response) {
}
#Override
protected void onCharReceived(final CharBuffer buf, final IOControl ioctrl) throws IOException {
while (buf.hasRemaining()) {
System.out.print(buf.get());
}
}
#Override
protected void releaseResources() {
}
#Override
protected Boolean buildResult(final HttpContext context) {
return Boolean.TRUE;
}
}
}
Use HttpURLConnection instead of httpClient.
final HttpURLConnection conn = (HttpURLConnection)url.openConnection();
final int bufferSize = 1024 * 1024;
conn.setChunkedStreamingMode(bufferSize);
final OutputStream out = conn.getOutputStream();

org.apache.http is deprecated, what to use?

I have an app that in order to download Json data uses org.apache.http
this is the class I use in order to make the request:
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
#SuppressWarnings("deprecation")
public class ServiceHandler {
static String response = null;
public final static int GET = 1;
public final static int POST = 2;
public ServiceHandler() {
}
/**
* Making service call
* #url - url to make request
* #method - http request method
* */
public String makeServiceCall(String url, int method) {
return this.makeServiceCall(url, method, null);
}
/**
* Making service call
* #url - url to make request
* #method - http request method
* #params - http request params
* */
public String makeServiceCall(String url, int method,
List<NameValuePair> params) {
try {
// http client
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
// Checking http request method type
if (method == POST) {
HttpPost httpPost = new HttpPost(url);
// adding post params
if (params != null) {
httpPost.setEntity(new UrlEncodedFormEntity(params));
}
httpResponse = httpClient.execute(httpPost);
} else if (method == GET) {
// appending params to url
if (params != null) {
String paramString = URLEncodedUtils
.format(params, "utf-8");
url += "?" + paramString;
}
HttpGet httpGet = new HttpGet(url);
httpResponse = httpClient.execute(httpGet);
}
httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity,HTTP.UTF_8);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
}
The problem is that every import from org.apache.http is deprecated and I don't know if i'll have problem using this class. Can someone point me to the right direction in order to "update" my class using non-deprecated methods?
EDIT:
From the Android M documentation:
This preview removes support for the Apache HTTP client. If your app is using this client and targets Android 2.3 (API level 9) or higher, use the HttpURLConnection class instead. This API is more efficient because it reduces network use through transparent compression and response caching, and minimizes power consumption. To continue using the Apache HTTP APIs, you must first declare the following compile-time dependency in your build.gradle file:
android {
useLibrary 'org.apache.http.legacy'
}
So my app will crash using that class right?
Instead of DefaultHttpClient use
HttpClient httpClient = HttpClientBuilder.create().build();
And Instead of HTTP.UTF_8 use
StandardCharsets.UTF_8
For HTTP.UTF_8 the alternative is Consts.UTF_8. It's weird they don't mention that in the docs. Consts.UTF_8 is a Charset whereas HTTP.UTF_8 is a String. HttpProtocolParams.setContentCharset(HttpParams httpParams, String charset) is expecting a String, not the Consts Charset.
For string we can use by String.valueOf(Consts.UTF_8)
Reference link

Bouncing between "Adapter is detached" and "No wrapped connection" with HttpClient

So as i said i'm bouncing back and forth between these two errors when trying to run HttpClient.execute(HttpPost). Getting IllegalStateException
public class NetMethods {
private static HttpClient client = new DefaultHttpClient();
public static void getStuff() {
ArrayList<Alarm> alarms = new ArrayList<Alarm>();
HttpPost post = HttpPostFactory.getHttpPost("GetStuff");
StringBuilder builder = new StringBuilder();
HttpResponse response = client.execute(post); // Exception thrown here
...
Also, my MttpPostFactory just has this
import org.apache.http.client.methods.HttpPost;
public class HttpPostFactory {
private static final String url = "http://example.com/ExampleFolder/";
public static HttpPost getHttpPost(String s) {
return new HttpPost(url + s);
}
}
This may arise from not closing the InputStream's you get from HttpClient, especially if arising from different threads...either not reading the whole content or calling the same HttpClient instance from two different threads.
I found solution from Androider's blog:
I got the log :
Invalid use of SingleClientConnManager: connection still allocated.
or
Caused by: java.lang.IllegalStateException: No wrapped connection.
or
Caused by: java.lang.IllegalStateException: Adapter is detached.
Finally got Solution:
public static DefaultHttpClient getThreadSafeClient() {
DefaultHttpClient client = new DefaultHttpClient();
ClientConnectionManager mgr = client.getConnectionManager();
HttpParams params = client.getParams();
client = new DefaultHttpClient(new ThreadSafeClientConnManager(params,
mgr.getSchemeRegistry()), params);
return client;
}
Try with this..
// Execute the asynctask with your URL
new myAsyncTask().execute("http://example.com/ExampleFolder/");
// Asynctask Callback method
private class myAsyncTask extends AsyncTask<String, Void, Void>
{
protected void onPreExecute()
{
super.onPreExecute();
}
#Override
protected Void doInBackground(String... arg0)
{
// Creating service handler class instance
ServiceHandler serhand = new ServiceHandler();
// Making a request to url and getting response
serhand.makeServiceCall(arg0[0], ServiceHandler.GET);
return null;
}
protected void onPostExecute(Void result)
{
}
}
// Service Handler class
package yourpagename
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
public class ServiceHandler {
static String response = null;
public final static int GET = 1;
public final static int POST = 2;
public ServiceHandler() {
}
/**
* Making service call
* #url - url to make request
* #method - http request method
* */
public String makeServiceCall(String url, int method) {
return this.makeServiceCall(url, method, null);
}
/**
* Making service call
* #url - url to make request
* #method - http request method
* #params - http request params
* */
public String makeServiceCall(String url, int method,
List<NameValuePair> params) {
try {
// http client
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
// Checking http request method type
if (method == POST) {
HttpPost httpPost = new HttpPost(url);
// adding post params
if (params != null) {
httpPost.setEntity(new UrlEncodedFormEntity(params));
}
httpResponse = httpClient.execute(httpPost);
} else if (method == GET) {
// appending params to url
if (params != null) {
String paramString = URLEncodedUtils
.format(params, "utf-8");
url += "?" + paramString;
}
HttpGet httpGet = new HttpGet(url);
httpResponse = httpClient.execute(httpGet);
}
httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
}

Android project using httpclient --> http.client (apache), post/get method

I'm doing a Get and Post method for an android project and I need to "translate" HttpClient 3.x to HttpClient 4.x (using by android).
My problem is that I'm not sure of what I have done and I don't find the "translation" of some methods...
This is the HttpClient 3.x I have done and (-->) the HttpClient 4.x "translation" if I have found it (Only parties who ask me problems) :
HttpState state = new HttpState (); --> ?
HttpMethod method = null; --> HttpUriRequest httpUri = null;
method.abort(); --> httpUri.abort(); //httpUri is a HttpUriRequest
method.releaseConnection(); --> conn.disconnect(); //conn is a HttpURLConnection
state.clearCookies(); --> cookieStore.clear(); //cookieStore is a BasicCookieStore
HttpClient client = new HttpClient(); --> DefaultHttpClient client = new DefaultHttpClient();
client.getHttpConnectionManager().getParams().setConnectionTimeout(SOCKET_TIMEOUT) --> HttpConnectionParams.setConnectionTimeout(param, SOCKET_TIMEOUT);
client.setState(state); --> ?
client.getParams().setCookiePolicy(CookiePolicy.RFC_2109); --> HttpClientParams.setCookiePolicy(param, CookiePolicy.RFC_2109);
PostMethod post = (PostMethod) method; --> ?
post.setRequestHeader(...,...); --> conn.setRequestProperty(...,...);
post.setFollowRedirects(false); --> conn.setFollowRedirects(false);
RequestEntity tmp = null; --> ?
tmp = new StringRequestEntity(...,...,...); --> ?
int statusCode = client.executeMethod(post); --> ?
String ret = method.getResponsBodyAsString(); --> ?
Header locationHeader = method.getResponseHeader(...); --> ?
ret = getPage(...,...); --> ?
I don't know if that is correct.
This has caused problems because the packages are not named similarly, and some methods too.
I just need documentation (I haven't found) and little help.
Here are the HttpClient 4 docs, that is what Android is using (4, not 3, as of 1.0->2.x). The docs are hard to find (thanks Apache ;)) because HttpClient is now part of HttpComponents (and if you just look for HttpClient you will normally end up at the 3.x stuff).
Also, if you do any number of requests you do not want to create the client over and over again. Rather, as the tutorials for HttpClient note, create the client once and keep it around. From there use the ThreadSafeConnectionManager.
I use a helper class, for example something like HttpHelper (which is still a moving target - I plan to move this to its own Android util project at some point, and support binary data, haven't gotten there yet), to help with this. The helper class creates the client, and has convenience wrapper methods for get/post/etc. Anywhere you USE this class from an Activity, you should create an internal inner AsyncTask (so that you do not block the UI Thread while making the request), for example:
private class GetBookDataTask extends AsyncTask<String, Void, Void> {
private ProgressDialog dialog = new ProgressDialog(BookScanResult.this);
private String response;
private HttpHelper httpHelper = new HttpHelper();
// can use UI thread here
protected void onPreExecute() {
dialog.setMessage("Retrieving HTTP data..");
dialog.show();
}
// automatically done on worker thread (separate from UI thread)
protected Void doInBackground(String... urls) {
response = httpHelper.performGet(urls[0]);
// use the response here if need be, parse XML or JSON, etc
return null;
}
// can use UI thread here
protected void onPostExecute(Void unused) {
dialog.dismiss();
if (response != null) {
// use the response back on the UI thread here
outputTextView.setText(response);
}
}
}
The easiest way to answer my question is to show you the class that I made :
public class HTTPHelp{
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
private boolean abort;
private String ret;
HttpResponse response = null;
HttpPost httpPost = null;
public HTTPHelp(){
}
public void clearCookies() {
httpClient.getCookieStore().clear();
}
public void abort() {
try {
if(httpClient!=null){
System.out.println("Abort.");
httpPost.abort();
abort = true;
}
} catch (Exception e) {
System.out.println("HTTPHelp : Abort Exception : "+e);
}
}
public String postPage(String url, String data, boolean returnAddr) {
ret = null;
httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.RFC_2109);
httpPost = new HttpPost(url);
response = null;
StringEntity tmp = null;
httpPost.setHeader("User-Agent", "Mozilla/5.0 (X11; U; Linux " +
"i686; en-US; rv:1.8.1.6) Gecko/20061201 Firefox/2.0.0.6 (Ubuntu-feisty)");
httpPost.setHeader("Accept", "text/html,application/xml," +
"application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5");
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
try {
tmp = new StringEntity(data,"UTF-8");
} catch (UnsupportedEncodingException e) {
System.out.println("HTTPHelp : UnsupportedEncodingException : "+e);
}
httpPost.setEntity(tmp);
try {
response = httpClient.execute(httpPost,localContext);
} catch (ClientProtocolException e) {
System.out.println("HTTPHelp : ClientProtocolException : "+e);
} catch (IOException e) {
System.out.println("HTTPHelp : IOException : "+e);
}
ret = response.getStatusLine().toString();
return ret;
}
}
I used this tutorial to do my post method and thoses examples
Well, you can find documentation on that version of HTTPClient here; it's especially useful to go through the example scenarios they present.
I unfortunately don't know version 3 of HTTPClient so I can't give direct equivalences; I suggest you take what you're trying to do and look through their example scenarios.
package com.service.demo;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class WebServiceDemoActivity extends Activity
{
/** Called when the activity is first created. */
private static String SOAP_ACTION1 = "http://tempuri.org/GetSubscriptionReportNames";//"http://tempuri.org/FahrenheitToCelsius";
private static String NAMESPACE = "http://tempuri.org/";
private static String METHOD_NAME1 = "GetSubscriptionReportNames";//"FahrenheitToCelsius";
private static String URL = "http://icontrolusa.com:8040/iPhoneService.asmx?WSDL";
Button btnFar,btnCel,btnClear;
EditText txtFar,txtCel;
ArrayList<String> headlist = new ArrayList<String>();
ArrayList<String> reportlist = new ArrayList<String>();
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btnFar = (Button)findViewById(R.id.btnFar);
btnCel = (Button)findViewById(R.id.btnCel);
btnClear = (Button)findViewById(R.id.btnClear);
txtFar = (EditText)findViewById(R.id.txtFar);
txtCel = (EditText)findViewById(R.id.txtCel);
btnFar.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
//Initialize soap request + add parameters
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME1);
//Use this to add parameters
request.addProperty("Fahrenheit",txtFar.getText().toString());
//Declare the version of the SOAP request
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.setOutputSoapObject(request);
envelope.dotNet = true;
try {
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
//this is the actual part that will call the webservice
androidHttpTransport.call(SOAP_ACTION1, envelope);
// Get the SoapResult from the envelope body.
SoapObject result = (SoapObject)envelope.bodyIn;
if(result != null)
{
//Get the first property and change the label text
txtCel.setText(result.getProperty(0).toString());
Log.e("err ","output is :::: "+result.getProperty(0).toString());
parseSON();
}
else
{
Toast.makeText(getApplicationContext(), "No Response",Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
btnClear.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
txtCel.setText("");
txtFar.setText("");
}
});
}
private void parseSON() {
headlist.clear();
reportlist.clear();
String text = txtCel.getText().toString() ;//sb.toString();
Log.i("######", "###### "+text);
try{
JSONObject jobj = new JSONObject(text);
JSONArray jarr = jobj.getJSONArray("Head");
for(int i=0;i<jarr.length();i++){
JSONObject e = jarr.getJSONObject(i);
JSONArray names = e.names();
for(int j=0;j<names.length();j++){
String tagname = names.getString(j);
if (tagname.equals("ReportID")) {
headlist.add(e.getString("ReportID"));
}
if (tagname.equals("ReportName")) {
reportlist.add(e.getString("ReportName"));
}
}
}
} catch(JSONException e){
Log.e("retail_home", "Error parsing data "+e.toString());
}
Log.d("length ", "head lenght "+headlist.size());
Log.d("value is ", "frst "+headlist.get(0));
Log.d("length ", "name lenght "+reportlist.size());
Log.d("value is ", "secnd "+reportlist.get(0));
}
}

Categories

Resources