Wednesday, April 23, 2014

How to access the adnroid url return data, special! !


"Http://mascwt.oicp.net:7080/Monitoring/Data/getOrgData/"

Send a url address, hope experts can give access to url return data. This url is to return json data.
Returns can be accessed on a computer, I want to develop on android, but can not engage with the HttpClient .. android way.

Come on. . . Now others have been urging, I can not handle ah.
<-! Main posts under Banner (D4) -><-! Posts under the main text (D5) ->
Reply:
 
public static String getXMLString (String url) {
HttpClient hc = new DefaultHttpClient ();
HttpConnectionParams.setConnectionTimeout (hc.getParams (), 4000);
/ / HttpConnectionParams.setSoTimeout (hc.getParams (), 4000);
HttpGet request = new HttpGet (url);
HttpResponse response;
try {
response = hc.execute (request);
HttpEntity entity = response.getEntity ();
if (response.getStatusLine (). getStatusCode () == HttpStatus.SC_OK) {
return EntityUtils.toString (entity, HTTP.UTF_8);
} Else {
return null;
}
} Catch (ClientProtocolException e) {
e.printStackTrace ();
return null;
} Catch (IOException e) {
e.printStackTrace ();
return null;
}
}


Reply:
 public class WebServices {
public JSONObject RequestUrl (String url) {
JSONObject jsonResponse = null;
try {
DefaultHttpClient httpClient = new DefaultHttpClient ();
Log.v ("URL request", "--->" + url);
URI uri = new URI (url);
HttpGet httpget = new HttpGet (uri);
httpget.setHeader ("Accept", "application / json");
httpget.setHeader ("Content-type", "application / json; charset = utf-8");
HttpResponse response = httpClient.execute (httpget);
HttpEntity responseEntity = response.getEntity ();
String changeTIDRec = EntityUtils.toString (responseEntity);
System.out.println (changeTIDRec);
jsonResponse = new JSONObject (changeTIDRec);
Log.v ("WebService", "Response:" + jsonResponse);
} Catch (Exception e) {
e.printStackTrace ();
}
return jsonResponse;
}}

Reply:

Reply:
@ Override
public void onCreate (Bundle savedInstanceState) {
super.onCreate (savedInstanceState);
setContentView (R.layout.activity_main);
new AsyncTask () {

@ Override
protected Void doInBackground (Void. .. params) {
/ / TODO Auto-generated method stub
JSONObject jObject = getJSONfromURL ("http://mascwt.oicp.net:7080/Monitoring/Data/getOrgData/");
return null;
}
.} Execute ();
}
public JSONObject getJSONfromURL (String url) {

/ / Initialize
InputStream is = null;
String result = "";
JSONObject jArray = null;

/ / Http post
try {
HttpClient httpclient = new DefaultHttpClient ();
HttpPost httppost = new HttpPost (url);
HttpResponse response = httpclient.execute (httppost);
HttpEntity entity = response.getEntity ();
is = entity.getContent ();

} Catch (Exception e) {
Log.e ("log_tag", "Error in http connection" + e.toString ());
}

/ / Convert response to string
try {
BufferedReader reader = new BufferedReader (new InputStreamReader (
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder ();
String line = null;
while ((line = reader.readLine ())! = null) {
sb.append (line + "\ n");
}
is.close ();
result = sb.toString ();
} Catch (Exception e) {
Log.e ("log_tag", "Error converting result" + e.toString ());
}

/ / Parse string to JSON object
try {
jArray = new JSONObject (result);
} Catch (JSONException e) {
Log.e ("log_tag", "Error parsing data" + e.toString ());
}

return jArray;
Reply:
Online pile. . . Should not be a problem, a problem guestbook
Reply:
references, 5th Floor Bill_Ming reply:
online pile. . . Should not be a problem, a problem guestbook

For me the example given above, you look at the android machine access. I visited the simulator is normal, the phone will not work, nor is it to say no, that is occasionally successful.
Reply:
Reply
references, 4th Floor CSDN_Ask of:
@ Override
public void onCreate (Bundle savedInstanceState) {
super.onCreate (savedInstanceState);
setContentView (R.layout.activity_main);
new AsyncTask () {

@ Override
prot ......

I read your code. I would like to ask you these codes through the phone found it? I wrote the code to run in the simulator successfully run on the phone occasionally successful, they would often SocketException: Connection reset by peer.
Reply:
The data returned json format. . . Why are you the url, copied to the browser window, directly download files ah. . . .
Reply:
What is the way to get the. . get or post
Reply:
QQ1084366249.. . There are problems add my qq exchange
Reply:
The first layer, WebClient
 
public class WebClient {
/ / ...
public WebClient () {
Log.v (TAG, "initialize");
timeout = 5 * 1000;
bufferSize = 8192;
encode = "UTF-8";
httpParams = new BasicHttpParams ();
HttpConnectionParams.setConnectionTimeout (httpParams, timeout);
HttpConnectionParams.setSoTimeout (httpParams, timeout);
HttpConnectionParams.setSocketBufferSize (httpParams, bufferSize);
HttpClientParams.setRedirecting (httpParams, true);
httpClient = new DefaultHttpClient (httpParams);
}

public String doGet (String url) throws Exception {
return doGet (url, null);
}

public String doGet (String url, Map params)
throws Exception {
/ / Add QueryString
String paramStr = "";
if (params! = null) {
Iterator > iter = params.entrySet () iterator ();.
while (iter.hasNext ()) {
Entry entry = (Entry ) iter
. Next ();
paramStr + = "&" + entry.getKey () + "="
+ URLEncoder.encode (entry.getValue (), encode);
}
if (paramStr.length ()> 0)
paramStr.replaceFirst ("&", "?");
url + = paramStr;
}
/ / Create HttpGet object
HttpGet get = new HttpGet (url);
Log.i ("doGet" + "URL", url);
try {
String strResp = "";
/ / Initiate a request
HttpResponse resp = httpClient.execute (get);
if (resp.getStatusLine (). getStatusCode () == HttpURLConnection.HTTP_OK)
strResp = EntityUtils.toString (resp.getEntity ());
else
/ / If it is not OK to return StatusCode throws
throw new Exception ("Error Response:"
+ Resp.getStatusLine () toString ());.
Log.i ("doGet Response", strResp);
return strResp;
} Finally {
get.abort ();
}
}
/ / ...
}


The second layer, Services
 
public class MyServices extends Service {
private static final String TAG = "MyServices";

private WebClient client;

@ Override
public void onCreate () {
Log.v (TAG, "onCreate");
this.client = new WebClient ();
}

@ Override
public IBinder onBind (Intent intent) {
/ / TODO Auto-generated method stub
Log.v (TAG, "onBind");
return null;
}

@ Override
public void onStart (Intent intent, int startId) {
Log.v (TAG, "onStart");

if (intent! = null) {
final Bundle bundle = intent.getExtras ();
if (bundle! = null) {

int flag = bundle.getInt ("flag");
switch (flag) {
case 999: {
new Thread () {
@ Override
public void run () {
Log.v (TAG + "onStart", "mascwt");
mascwt ();
}
.} Start ();
break;
}
default:
Log.w (TAG + "onStart", "to match the case");
}

}
}

}

@ Override
public void onDestroy () {
super.onDestroy ();
Log.v (TAG, "onDestroy");
}

public void mascwt () {
String str = "";
try {
str = client.doGet ("http://mascwt.oicp.net:7080/Monitoring/Data/getOrgData/");
} Catch (Exception e) {
/ / TODO Auto-generated catch block
e.printStackTrace ();
}
Intent broadIntent = new Intent ();
broadIntent.setAction ("com.ytu.enetmobile.servicesBroadcast");
Bundle bundle = new Bundle ();
bundle.putString ("mascwt", str);
bundle.putInt ("flag", 999);
broadIntent.putExtras (bundle);
sendBroadcast (broadIntent);
}


}



The third layer, UI
 
public class ConnectionTestActivity extends Activity {
/ / ...
@ Override
public void onCreate (Bundle savedInstanceState) {
super.onCreate (savedInstanceState);
setContentView (R.layout.activity_connectiontest);

tv_1 = (TextView) this.findViewById (R.id.tv_1);

receiver = new DataReceiver ();
}

@ Override
public void onStart () {
super.onStart ();
if (null == receiver) {
receiver = new DataReceiver ();
}
IntentFilter filter = new IntentFilter () ;/ / create IntentFilter object
filter.addAction ("com.ytu.enetmobile.servicesBroadcast");
this.registerReceiver (receiver, filter);
}

public void onClick (View view) {
switch (view.getId ()) {
case R.id.button2: {
Intent intent = new Intent (
"Com.ytu.enetmobile.services.enetservices");
Bundle bundle = new Bundle ();
bundle.putInt ("flag", 999);
intent.putExtras (bundle);

startService (intent);
break;
}
}

}

class DataReceiver extends BroadcastReceiver {
public static final String TAG = "DataReceiver";

@ Override
public void onReceive (Context context, Intent intent) {
Bundle bundle = intent.getExtras ();
switch (bundle.getInt ("flag")) {
case 999: {
String str = intent.getStringExtra ("mascwt");
tv_1.setText (str);
break;
}
default:
Log.v (TAG + "onReceive", "does not match the case");
break;

}
}
}
}


The result

Test results:
Real test OK.
Garbled, presumably encoding issues.
Reply:
You see it posted in several days ...... it happens I did, took to the URL you tune a bit, in addition to encoding format is wrong, no big problem. Additionally above code may be incomplete, if discuss issues
Reply:
reference to the 9th floor Bill_Ming reply:
what way is acquired. . get or post

"Application / json"
Before the server using this code, because often times in order to request 7-8 run successfully on my phone, so I posted this in this post.
Later, the server side of the exchange, it is estimated there is a server configuration issue.
In fact, we request process, I understand that I can request is successful, the encoding is also no problem, but also to resolve it, just want to ask why will always appear
SocketException: Connection reset by peer
.The problem then I posted another message out, the source of which I requested data. And everyone else's.
Reply:
reference to the 11th floor btyh17mxy reply:
first layer, WebClient


Java code?



123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657

public class WebClient {/ / ... public WebClient () {......

Thank you very much. I have looked at the code again, the basic idea is the same, but it is also the result of your coding problems arising.
In fact, I doubt that the client and server HTTP header parameter configuration. Simulator data can be successful request to prove the upper code is right. Because my code is to take over other projects. While the program is running into the phone often occur SocketException: Connection reset by peer principle I read a lot about this error.
In fact, the error in: HttpResponse resp = httpClient.execute (get); so I wanted to ask is affected by this get parameter configuration, why simulators and computer browser can access, and mobile access will be wrong? When I am running often wrong, so I used a continuous requests, finally able to request the data. Ask, you are in the process of running the phone had no reported this wrong? ?


Reply:
reference to the second floor CSDN_Ask reply:
Java code 123456789101112131415161718192021public class WebServices {public JSONObject RequestUrl (String url) {JSONObject jsonResponse = null; try {DefaultHttpClient httpCl ...? ...
Do not use EntityUtils.toString method - a restricted length of this method, the best way to achieve their own conversion
Reply:
reference to the 14th floor tesky0125 reply:
reference to the 11th floor btyh17mxy reply: the first layer, WebClient


Java code?



123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657

public class WebCli ......

My server is WCF in 2.3 and 4.0 mobile phones and virtual machines are tested, like you error did not occur. It is convenient to look
code stickers
Reply:
cited 15 floor haoxiang12345 reply:
reference to the second floor CSDN_Ask reply:
Java code 123456789101112131415161718192021public class WebServices {public JSONObject RequestUrl (String url) {JSONObject jsonResponse = null;? Try {DefaultHttpClie ......


http://bbs.csdn.net/topics/390253540
The above address is my other post about the same issue. There are two replies to my source. You can look at. Server. Net MVC, I do not know the details. Only the url address.
Reply:
reference to the 13th floor tesky0125 reply:
reference to the 9th floor Bill_Ming Re: What is the way to get the. . get or post
"Application / json"
Before the server using this code, because often times in order to request 7-8 run successfully on my phone, so I posted this in this post.
Later, the server side of the exchange, it is estimated there is a server configuration issue.
In fact, we request process, I understand that I can request is successful, the encoding is also no problem, but also to resolve it, just want to ask why ......


You put that pile to try to turn off anti-virus software
Reply:
Now resolved not, recently encountered this problem.
Reply:

No comments:

Post a Comment