Tuesday, November 25, 2014

android get and post url content code sample

1.code

package com.pkrss.helper;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map;

public class WebHelper {

public static String GetPageContent(String pageURL)
{
return _GetRemotePageContent("GET",pageURL,null);
}

public static String GetPostPageContent(String pageURL,Map<String,String> parameters)
{
return _GetRemotePageContent("POST",pageURL,parameters);
}

private static String _GetRemotePageContent(String method,String pageURL,Map<String,String> parameters)
{
String pageContent="";
BufferedReader in = null;
InputStreamReader isr = null;
InputStream is = null;
HttpURLConnection huc = null;

try
{

String strparam = "";

if(parameters != null){
for(Map.Entry<String,String> item : parameters.entrySet()){
if(strparam != "")
strparam += "&";
strparam += URLEncoder.encode(item.getKey(), "UTF-8") + "=" + URLEncoder.encode(item.getValue(), "UTF-8");
}
}

if(strparam!=null && strparam.length()>0 && method.equals("GET")){
if(pageURL.contains("?"))
pageURL += "&";
else
pageURL += "?";

pageURL += strparam;
}

URL url = new URL(pageURL);
huc = (HttpURLConnection)url.openConnection();

huc.setRequestMethod(method);

if(method.equals("POST")){
huc.setDoOutput(true);
huc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

OutputStreamWriter request = new OutputStreamWriter(huc.getOutputStream());

request.write(strparam);
request.flush();
request.close();
}

is = huc.getInputStream();

isr = new InputStreamReader(is,"UTF-8");
in = new BufferedReader(isr);
String line = null;
while(((line = in.readLine()) != null))
{
if(line.length()==0)
continue;
pageContent+=line; // + "\n";
}
}
catch (Exception e)
{
// e.printStackTrace();
}
finally
{
try
{
is.close(); isr.close();in.close();huc.disconnect();
}
catch (Exception e) {}
}
return pageContent;
}

}



2.Thanks

No comments: