How to switch from HttpClient to HttpUrlConnection? - java

I am creating an Android application and I send data from Android application to servlet through HttpClient. I use HttpPost method.
I read in Android developer site that Apache HttpClient library has some bug in Android Froyo 2.2 and after all it's good practice to use HttpUrlConnection instead HttpPost. So I want to convert my HttpPost code to HttpUrlConnectio but don't know how.
I am posting my Android code as well as servlet code here
Android code
private String postData(String valueIWantToSend[])
{
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
try
{
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("param1",valueIWantToSend[0]));
nameValuePairs.add(new BasicNameValuePair("param2", valueIWantToSend[1]));
nameValuePairs.add(new BasicNameValuePair("param3", valueIWantToSend[2]));
nameValuePairs.add(new BasicNameValuePair("param4", valueIWantToSend[3]));
nameValuePairs.add(new BasicNameValuePair("param5", valueIWantToSend[4]));
nameValuePairs.add(new BasicNameValuePair("param6", valueIWantToSend[5]));
nameValuePairs.add(new BasicNameValuePair("param7", valueIWantToSend[6]));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
/* execute */
HttpResponse response = httpclient.execute(httppost);
HttpEntity rp = response.getEntity();
//origresponseText=readContent(response);
}
catch (ClientProtocolException e)
{
// TODO Auto-generated catch block
}
catch (IOException e)
{
// TODO Auto-generated catch block
}
return null;
}
and here is my servlet code
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html");
ObjectOutputStream out = new ObjectOutputStream(response.getOutputStream());
Enumeration paramNames = request.getParameterNames();
String params[] = new String[7];
int i=0;
while(paramNames.hasMoreElements())
{
String paramName = (String) paramNames.nextElement();
System.out.println(paramName);
String[] paramValues = request.getParameterValues(paramName);
params[i] = paramValues[0];
System.out.println(params[i]);
i++;
}
}

When I read the already mentioned Google post about best practices doing HTTP requests in newer versions of Android, I thought somebody was kidding me. HttpURLConnection is really a nightmare to use, compared to almost any other way to communicate with HTTP servers (apart from direct Socket communication).
I didn't find a really slim library for Android to do the heavy lifting, so I wrote my own. You can find it at DavidWebb including a list of alternative libraries which I found (unfortunately) after developing the library.
Your code would look more or less like this:
public void testPostToUrl() throws Exception {
String[] values = new String[3];
Webb webb = Webb.create();
Response<String> response = webb
.post("http://www.example.com/abc.php")
.param("param1", values[0])
.param("param2", values[1])
.param("param3", values[2])
.asString();
assertEquals(200, response.getStatusCode());
assertNotNull(response.getBody());
assertTrue(response.getBody().contains("my expected result"));
}
public void testPostToUrlShorter() throws Exception {
String[] values = new String[3];
Webb webb = Webb.create();
String result = webb
.post("http://www.example.com/abc.php")
.param("param1", values[0])
.param("param2", values[1])
.param("param3", values[2])
.ensureSuccess()
.asString()
.getBody();
assertTrue(result.contains("my expected result"));
}

You should absolutely be using HttpUrlConnection:
For Gingerbread and better, HttpURLConnection is the best choice... New applications should use HttpURLConnection...
--Google (circa. 2011)
However, there is no easy way just to "switch". The APIs are totally different. You are going to have to rewrite your networking code. There are perfect examples in the documentation on how to submit a GET and POST requests as well as in the SDK sample apps.

You don't have to switch, you can continue using apache's library like I described in this answer. There are really no downsides to continue using apache's library - it's only google's marketing.

Related

Use Java to get Github repositories

I'm using the following code to send a http request to github.
String url = "https://api.github.com/repositories";
try {
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
HttpPost request = new HttpPost(url);
// StringEntity params = new StringEntity(body);
request.addHeader("content-type", "application/json");
// request.setEntity(params);
HttpResponse result = httpClient.execute(request);
String json = EntityUtils.toString(result.getEntity(), "UTF-8");
System.out.println(json);
} catch (IOException ex) {
}
I got output: {"message":"Not Found","documentation_url":"https://developer.github.com/v3"}
If use directly put "https://api.github.com/repositories" in browser, a lot of useful information will be shown. My question is how can I get the information I see when using browser by using Java.
You should use HttpGet instead of HttpPost. Just like your browser sends a GET request.

How to connect Android app with MySQL database through PHP

I am still a little skeptical as to how to connect my Android app to a PHP script. I saw somewhere that the following code will connect the app to the server. But I am new at android so I do not know how to really use it.
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("http://url.to.my.app.com");
HttpResponse response = httpClient.execute(httpGet);
// handle response'
I understand that this opens a connection to an online server, but what I do not understand is what kind of response is returned by the server and how to process it. Also, I want to know how to send data through POST to the server from my app.
(If you could provide some code of your own, that would be helpful too) Thanks!
This will open a connection and send a http GET request to server. Your PHP script executes on the server side for this request and returns some contents. You can use folowing code to process the response.
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
String result = RestClient.convertStreamToString(instream);
}
For POST execution you need to do something like this.
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");
try {
// Add your data
List <NameValuePair> nvps = new ArrayList <NameValuePair>();
nvps.add(new BasicNameValuePair("test1","test1" ));
nvps.add(new BasicNameValuePair("test2", "test2" ));
httppost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}

how to send cURL in Android to REST service

I'm newbie in android, I want to get some data from my REST service, but I have some problem to initialize the method what's I send into the my REST service. you know that REST service using cURL to manipulate some data(POST,PUT,GET,DELETE). now how to send POST PUT GET DELETE method via cURL in android. do same as using httppost to send it? or how to send cURL to rest service in android?
Using HttpClient you can send POST,PUT,GET,DELETE requests. For an example POST request check here.
public void postData() {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "12345"));
nameValuePairs.add(new BasicNameValuePair("stringdata", "AndDev is Cool!"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
// Newventuresmarket.com
// Steven Koelsche`
Thanks Brak.
Mars you might need to adjust headers also if needed for cURL...
try {
httppost.setHeader("Content-Type", "application/json");
httppost.setHeader("Accept", "application/json");

Android https form submission?

Hi I'm having a lot of trouble submitting a simple form, I have searched around and it appears quite a few people have had the same problem but I haven't found an answer.
Here's my code so far:
public void postData(TextView txtResult, String user, String pass) throws ClientProtocolException, IOException {
HttpPost post = new HttpPost("https://www.mymeteor.ie");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("username", user));
nameValuePairs.add(new BasicNameValuePair("userpass", pass));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(post);
HttpEntity entity = response.getEntity();
String responseText = EntityUtils.toString(entity);
txtResult.setText(responseText);
}
The above code will simply return the original page,
can anybody help me?
thanks
Are you sure that URL supports logging in via post that way? It looks to me like the login form sends the post data to this URL: https://www.mymeteor.ie/go/mymeteor-login-manager
I would also suspect you should be using some sort of API instead of just posting data to their login form, remotely.

Android, Java: HTTP POST Request

I have to do a http post request to a web-service for authenticating the user with username and password. The Web-service guy gave me following information to construct HTTP Post request.
POST /login/dologin HTTP/1.1
Host: webservice.companyname.com
Content-Type: application/x-www-form-urlencoded
Content-Length: 48
id=username&num=password&remember=on&output=xml
The XML Response that i will be getting is
<?xml version="1.0" encoding="ISO-8859-1"?>
<login>
<message><![CDATA[]]></message>
<status><![CDATA[true]]></status>
<Rlo><![CDATA[Username]]></Rlo>
<Rsc><![CDATA[9L99PK1KGKSkfMbcsxvkF0S0UoldJ0SU]]></Rsc>
<Rm><![CDATA[b59031b85bb127661105765722cd3531==AO1YjN5QDM5ITM]]></Rm>
<Rl><![CDATA[username#company.com]]></Rl>
<uid><![CDATA[3539145]]></uid>
<Rmu><![CDATA[f8e8917f7964d4cc7c4c4226f060e3ea]]></Rmu>
</login>
This is what i am doing HttpPost postRequest = new HttpPost(urlString); How do i construct the rest of the parameters?
Here's an example previously found at androidsnippets.com (the site is currently not maintained anymore).
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "12345"));
nameValuePairs.add(new BasicNameValuePair("stringdata", "AndDev is Cool!"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
So, you can add your parameters as BasicNameValuePair.
An alternative is to use (Http)URLConnection. See also Using java.net.URLConnection to fire and handle HTTP requests. This is actually the preferred method in newer Android versions (Gingerbread+). See also this blog, this developer doc and Android's HttpURLConnection javadoc.
to #BalusC answer I would add how to convert the response in a String:
HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
String result = RestClient.convertStreamToString(instream);
Log.i("Read from server", result);
}
Here is an example of convertStramToString.
Please consider using HttpPost. Adopt from this: http://www.javaworld.com/javatips/jw-javatip34.html
URLConnection connection = new URL("http://webservice.companyname.com/login/dologin").openConnection();
// Http Method becomes POST
connection.setDoOutput(true);
// Encode according to application/x-www-form-urlencoded specification
String content =
"id=" + URLEncoder.encode ("username") +
"&num=" + URLEncoder.encode ("password") +
"&remember=" + URLEncoder.encode ("on") +
"&output=" + URLEncoder.encode ("xml");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
// Try this should be the length of you content.
// it is not neccessary equal to 48.
// content.getBytes().length is not neccessarily equal to content.length() if the String contains non ASCII characters.
connection.setRequestProperty("Content-Length", content.getBytes().length);
// Write body
OutputStream output = connection.getOutputStream();
output.write(content.getBytes());
output.close();
You will need to catch the exception yourself.
I'd rather recommend you to use Volley to make GET, PUT, POST... requests.
First, add dependency in your gradle file.
compile 'com.he5ed.lib:volley:android-cts-5.1_r4'
Now, use this code snippet to make requests.
RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
StringRequest postRequest = new StringRequest( com.android.volley.Request.Method.POST, mURL,
new Response.Listener<String>()
{
#Override
public void onResponse(String response) {
// response
Log.d("Response", response);
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
// error
Log.d("Error.Response", error.toString());
}
}
) {
#Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<String, String>();
//add your parameters here as key-value pairs
params.put("username", username);
params.put("password", password);
return params;
}
};
queue.add(postRequest);
Try HttpClient for Java:
http://hc.apache.org/httpclient-3.x/
You can reuse the implementation I added to ACRA:
http://code.google.com/p/acra/source/browse/tags/REL-3_1_0/CrashReport/src/org/acra/HttpUtils.java?r=236
(See the doPost(Map, Url) method, working over http and https even with self signed certs)
I used the following code to send HTTP POST from my android client app to C# desktop app on my server:
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "12345"));
nameValuePairs.add(new BasicNameValuePair("stringdata", "AndDev is Cool!"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
I worked on reading the request from a C# app on my server (something like a web server little application).
I managed to read request posted data using the following code:
server = new HttpListener();
server.Prefixes.Add("http://*:50000/");
server.Start();
HttpListenerContext context = server.GetContext();
HttpListenerContext context = obj as HttpListenerContext;
HttpListenerRequest request = context.Request;
StreamReader sr = new StreamReader(request.InputStream);
string str = sr.ReadToEnd();
HTTP request POST in java does not dump the answer?
public class HttpClientExample
{
private final String USER_AGENT = "Mozilla/5.0";
public static void main(String[] args) throws Exception
{
HttpClientExample http = new HttpClientExample();
System.out.println("\nTesting 1 - Send Http POST request");
http.sendPost();
}
// HTTP POST request
private void sendPost() throws Exception {
String url = "http://www.wmtechnology.org/Consultar-RUC/index.jsp";
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
// add header
post.setHeader("User-Agent", USER_AGENT);
List<NameValuePair> urlParameters = new ArrayList<>();
urlParameters.add(new BasicNameValuePair("accion", "busqueda"));
urlParameters.add(new BasicNameValuePair("modo", "1"));
urlParameters.add(new BasicNameValuePair("nruc", "10469415177"));
post.setEntity(new UrlEncodedFormEntity(urlParameters));
HttpResponse response = client.execute(post);
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + post.getEntity());
System.out.println("Response Code : " +response.getStatusLine().getStatusCode());
BufferedReader rd = new BufferedReader(new
InputStreamReader(response.getEntity().getContent()));
StringBuilder result = new StringBuilder();
String line = "";
while ((line = rd.readLine()) != null)
{
result.append(line);
System.out.println(line);
}
}
}
This is the web: http://www.wmtechnology.org/Consultar-RUC/index.jsp,from you can consult Ruc without captcha. Your opinions are welcome!

Categories