我尝试使用asyncTask将我的Android应用程序连接到Web服务器,但我无法实现。 在代码中,我需要使用asyncTask检查互联网连接。请提供一些代码以便应用连接到任何网络服务器
我使用了两个java类和两个xml文件。
MainActivity和问候。
MainActivity.java
public class MainActivity extends Activity implements OnClickListener{
// Variable Declaration
Context context=this;
private RadioGroup r1,r2,r4,r3,r5;
private RadioButton rb1,rb2,rb3,rb4,rb5;
private String welcome,service,clean,knowledge,visit,responses,remarks,tq;
String food,rate;
int a1,a2,a3,a4,a5;
ProgressDialog dialog;
EditText text;
Button button;
RatingBar ra1,ra2;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(android.os.Build.VERSION.SDK_INT>9)
{
StrictMode.enableDefaults();
}
typeface();
init();
}
private void typeface() {
// TODO Auto-generated method stub
Typeface type=Typeface.createFromAsset(getAssets(), "fonts/font.otf");
TextView tv=(TextView) findViewById(R.id.textView);
tv.setTypeface(type);
}
// Checking Internet Connection
// Variable Initialisation
private void init() {
// TODO Auto-generated method stub
button=(Button) findViewById(R.id.button1);
ra1=(RatingBar) findViewById(R.id.rating1);
ra2=(RatingBar) findViewById(R.id.rating2);
r1=(RadioGroup) findViewById(R.id.radioGroup1);
r2=(RadioGroup) findViewById(R.id.radioGroup2);
r3=(RadioGroup) findViewById(R.id.radioGroup3);
r4=(RadioGroup) findViewById(R.id.radioGroup4);
text.setVerticalScrollBarEnabled(true);
r5=(RadioGroup) findViewById(R.id.radioGroup5);
text=(EditText) findViewById(R.id.editText1);
button.setOnClickListener(this);
ra1=(RatingBar) findViewById(R.id.rating1);
ra2=(RatingBar) findViewById(R.id.rating2);
// RadioButton Listeners
r1.setOnCheckedChangeListener(new OnCheckedChangeListener(){
@Override
public void onCheckedChanged(RadioGroup r1, int arg1) {
// TODO Auto-generated method stub
int a=r1.getCheckedRadioButtonId();
rb1=(RadioButton) findViewById(a);
welcome=rb1.getText().toString();
}
});
r2.setOnCheckedChangeListener(new OnCheckedChangeListener(){
@Override
public void onCheckedChanged(RadioGroup r2, int arg2) {
// TODO Auto-generated method stub
int b=r2.getCheckedRadioButtonId();
rb2=(RadioButton) findViewById(b);
service=rb2.getText().toString();
}
});
r3.setOnCheckedChangeListener(new OnCheckedChangeListener(){
@Override
public void onCheckedChanged(RadioGroup r3, int arg3) {
// TODO Auto-generated method stub
int c=r3.getCheckedRadioButtonId();
rb3=(RadioButton) findViewById(c);
clean=rb3.getText().toString();
}
});
r4.setOnCheckedChangeListener(new OnCheckedChangeListener(){
@Override
public void onCheckedChanged(RadioGroup r4, int arg4) {
// TODO Auto-generated method stub
int d=r4.getCheckedRadioButtonId();
rb4=(RadioButton) findViewById(d);
knowledge=rb4.getText().toString();
}
});
r5.setOnCheckedChangeListener(new OnCheckedChangeListener(){
@Override
public void onCheckedChanged(RadioGroup r5, int arg5) {
// TODO Auto-generated method stub
int e=r5.getCheckedRadioButtonId();
rb5=(RadioButton) findViewById(e);
visit=rb5.getText().toString();
}
});
ra1.setOnRatingBarChangeListener(new OnRatingBarChangeListener(){
@Override
public void onRatingChanged(RatingBar ra1, float rating, boolean arg2) {
// TODO Auto-generated method stub
rating=ra1.getRating();
food=String.valueOf(rating);
}
});
ra2.setOnRatingBarChangeListener(new OnRatingBarChangeListener(){
@Override
public void onRatingChanged(RatingBar ra2, float rating, boolean arg2) {
// TODO Auto-generated method stub
rating=ra2.getRating();
rate=String.valueOf(rating);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
// Button onClick Listener
@Override
public void onClick(View v) {
// TODO Auto-generated method stub\
dialog=ProgressDialog.show(MainActivity.this, "Please Wait", "Sending...");
//Creating a new thread for sending mail
remarks=text.getText().toString();
final Thread thread=new Thread(new Runnable(){
@Override
public void run() {
// TODO Auto-generated method stub
try{
sendMail();
}
catch(Exception e){
Log.e("Error", "Connecting");
}
}
});thread.start();
}
// sendMail using post method
protected void sendMail() {
// TODO Auto-generated method stub
try{
InputStream is=null;
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://wertualdesigners.com/siesta/mail/mail.php");
try {
List<NameValuePair> nvp = new ArrayList<NameValuePair>();
nvp.add(new BasicNameValuePair("welcome",welcome));
nvp.add(new BasicNameValuePair("service",service));
nvp.add(new BasicNameValuePair("clean",clean));
nvp.add(new BasicNameValuePair("knowledge",knowledge));
nvp.add(new BasicNameValuePair("visit",visit));
nvp.add(new BasicNameValuePair("food",food));
nvp.add(new BasicNameValuePair("remarks",remarks));
nvp.add(new BasicNameValuePair("rate",rate));
httppost.setEntity(new UrlEncodedFormEntity(nvp));
HttpResponse response=httpclient.execute(httppost);
HttpEntity entity=response.getEntity();
is=entity.getContent();
}
catch(Exception e){
Log.e("Error","Network problem",e);
} try{
BufferedReader reader=new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb=new StringBuilder();
String line="";
while((line=reader.readLine())!=null){
sb.append(line +"\n");
}
is.close();
responses=sb.toString();
tq=responses.toString();
text.setText(tq);
}
catch(Exception e){
}
Intent i=new Intent(this,greetings.class);
i.putExtra("key", tq);
startActivity(i);
}
catch(Exception e){
Log.e("Error", "No response");
}
dialog.dismiss();
}
public void onPause(){
super.onPause();
finish();
}
}
Greetings.java
package com.example.formapp;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.StrictMode;
import android.widget.TextView;
public class greetings extends Activity{
String greet;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.greetings);
if(android.os.Build.VERSION.SDK_INT>9)
{
StrictMode.enableDefaults();
}
TextView v=(TextView) findViewById(R.id.t);
Intent i=getIntent();
greet=i.getStringExtra("key").toString();
// TODO Auto-generated method stub
Typeface type=Typeface.createFromAsset(getAssets(), "fonts/font.otf");
v.setTypeface(type);
v.setText(greet);
}
@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
finish();
}
}
activity_main.xml
<LinearLayout android:layout_height="match_parent"
android:layout_width="match_parent"
android:orientation="vertical" android:weightSum="1"
xmlns:android="http://schemas.android.com/apk/res/android"
>
<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:background="#CCCCCC"
android:gravity="center"
android:text="Feedback Form"
android:textSize="25sp"
/>
<ScrollView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight=".25" >
<LinearLayout android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_marginLeft="6dp"
android:layout_marginTop="3dp"
android:layout_marginRight="3dp">
<TextView
android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Did our staff make you feel welcome upon arrival?"
android:typeface="monospace"
android:textSize="16dp"
android:textAppearance="?android:attr/textAppearanceLarge" />
<RadioGroup
android:id="@+id/radioGroup1"
android:layout_width="match_parent"
android:orientation="horizontal"
android:layout_height="wrap_content">
<RadioButton
android:id="@+id/radioButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" android:textSize="15sp"
android:text="Yes" android:layout_marginLeft="40dp" />
<RadioButton
android:id="@+id/radioButton2"
android:layout_width="wrap_content"
android:layout_height="wrap_content" android:textSize="15sp"
android:text="No" android:layout_marginLeft="40dp" />
</RadioGroup>
<TextView
android:id="@+id/textView2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Was our service prompt?"
android:typeface="monospace"
android:textSize="16sp"
android:textAppearance="?android:attr/textAppearanceLarge" />
<RadioGroup
android:id="@+id/radioGroup2"
android:layout_width="match_parent" android:orientation="horizontal"
android:layout_height="wrap_content" >
<RadioButton
android:id="@+id/radioButton3"
android:layout_width="wrap_content"
android:layout_height="wrap_content" android:textSize="15sp"
android:text="Yes" android:layout_marginLeft="40dp" />
<RadioButton
android:id="@+id/radioButton4"
android:layout_width="wrap_content"
android:layout_height="wrap_content" android:textSize="15sp"
android:text="No" android:layout_marginLeft="40dp" />
</RadioGroup>
<TextView
android:id="@+id/textView4"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Was your room clean and well supplied ?"
android:typeface="monospace"
android:textSize="16sp"
android:textAppearance="?android:attr/textAppearanceLarge" />
<RadioGroup
android:id="@+id/radioGroup3"
android:layout_width="match_parent" android:orientation="horizontal"
android:layout_height="wrap_content">
<RadioButton
android:id="@+id/radioButton5"
android:layout_width="wrap_content"
android:layout_height="wrap_content" android:textSize="15sp"
android:text="Yes" android:layout_marginLeft="40dp" />
<RadioButton
android:id="@+id/radioButton6"
android:layout_width="wrap_content"
android:layout_height="wrap_content" android:textSize="15sp"
android:text="No" android:layout_marginLeft="40dp" />
</RadioGroup>
<TextView
android:id="@+id/textView3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Quality of Food "
android:typeface="monospace"
android:textSize="16sp"
android:textAppearance="?android:attr/textAppearanceLarge" />
<RatingBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:id="@+id/rating1"
android:numStars="5"/>
<Space android:layout_width="match_parent" android:layout_height="10dp" />
<TextView
android:id="@+id/textView3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Were our staffs knowledgeable?"
android:typeface="monospace"
android:textSize="16sp"
android:textAppearance="?android:attr/textAppearanceLarge" />
<RadioGroup
android:id="@+id/radioGroup4"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<RadioButton
android:id="@+id/radioButton7"
android:layout_width="wrap_content"
android:layout_height="wrap_content" android:textSize="15sp"
android:text="Yes" android:layout_marginLeft="40dp" />
<RadioButton
android:id="@+id/radioButton8"
android:layout_width="wrap_content"
android:layout_height="wrap_content" android:textSize="15sp"
android:text="No" android:layout_marginLeft="40dp" />
</RadioGroup>
<TextView
android:id="@+id/textView5"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Would you visit us again?"
android:typeface="monospace"
android:textSize="16sp"
android:textAppearance="?android:attr/textAppearanceLarge" />
<RadioGroup
android:id="@+id/radioGroup5"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<RadioButton
android:id="@+id/radioButton9"
android:layout_width="wrap_content"
android:layout_height="wrap_content" android:textSize="15sp"
android:text="Yes" android:layout_marginLeft="40dp" />
<RadioButton
android:id="@+id/radioButton10"
android:layout_width="wrap_content"
android:layout_height="wrap_content" android:textSize="15sp"
android:text="No" android:layout_marginLeft="40dp" />
</RadioGroup>
<TextView
android:id="@+id/textView6"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="How do we rate?"
android:typeface="monospace"
android:textSize="16sp"
android:textAppearance="?android:attr/textAppearanceLarge" />
<RatingBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:id="@+id/rating2"
android:numStars="5"/>
<Space android:layout_width="match_parent" android:layout_height="10dp"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Suggestions/Remarks"
android:textSize="16sp"
android:typeface="monospace"/>
<EditText android:id="@+id/editText1"
android:typeface="monospace"
android:layout_width="match_parent"
android:layout_height="70dp"
android:inputType="text"
android:hint="Maximum 100 Words"
android:maxLength="100"
android:scrollHorizontally="false"
android:scrollbars="vertical" />
</LinearLayout>
</ScrollView>
<LinearLayout
android:layout_height="match_parent"
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_weight=".75">
<Button
android:id="@+id/button1"
android:text="Submit"
android:textSize="20dp"
android:layout_width="120dp"
android:background="@drawable/buttonshape"
android:textColor="#FFFFFF"
android:textStyle="bold"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:shadowRadius="5"
android:typeface="monospace"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="We would highly appreciate your valuable feedback"
android:gravity="center"
android:textSize="12dp"
android:layout_gravity="center_horizontal"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:layout_gravity="center_horizontal"
android:text="---Greetings from siesta super stay"
android:textStyle="italic" />
</LinearLayout>
</LinearLayout>
greetigs.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
android:layout_height="fill_parent"
android:layout_width="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android" >
<TextView
android:id="@+id/t"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:layout_margin="10dp"
android:typeface="monospace"
android:textStyle="italic"
android:textAppearance="?android:attr/textAppearanceLarge" />
<ImageView
android:id="@+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/t"
android:layout_centerHorizontal="true"
/>
</RelativeLayout>
答案 0 :(得分:0)
您是否在清单文件中设置了权限?这是一个非常常见的错误。
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
毕竟我认为developer.android.com是最好的资源和最好的解释,我建议你一步一步地走过this。
答案 1 :(得分:0)
这是我的基本HTTPS AsyncTask,强制GZip:
package using_net;
import android.content.Context;
import android.os.AsyncTask;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.conn.ssl.X509HostnameVerifier;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.SingleClientConnManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.GZIPInputStream;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import logger.AndroidLogger;
import other.GetException;
import other.PostException;
/**
* Created by ehog on 2013.12.11..
*/
public class BaseAsyncTask<Paramets, Progress,Result> extends AsyncTask<Paramets,Progress,Result>
{
protected Context _context;
public BaseAsyncTask(Context context)
{
_context = context;
}
protected String Get(String url) throws GetException
{
try
{
AndroidLogger.PushDebugMessage("Web access: "+url);
URL realUrl = new URL(url);
URLConnection connection = realUrl.openConnection();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder builder = new StringBuilder();
for(String line = null; (line = reader.readLine()) != null;) {
builder.append(line);
}
return builder.toString();
}
catch (Exception e) {
throw new GetException(e);
}
}
protected String Post(String url, String message_json) throws PostException
{
HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
DefaultHttpClient client = new DefaultHttpClient();
SchemeRegistry registry = new SchemeRegistry();
SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory();
socketFactory.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier);
registry.register(new Scheme("https", socketFactory, 443));
SingleClientConnManager mgr = new SingleClientConnManager(client.getParams(), registry);
HttpClient httpclient = new DefaultHttpClient(mgr, client.getParams());
HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);
HttpPost httpost = new HttpPost(url);
try
{
List<NameValuePair> nvp = new ArrayList<NameValuePair>(1);
nvp.add(new BasicNameValuePair("json_data",message_json));
httpost.setHeader("User-Agent", "Your.browser.header");
httpost.setEntity(new UrlEncodedFormEntity(nvp, HTTP.UTF_8));
httpost.addHeader("Accept-Encoding", "gzip");
HttpResponse response = httpclient.execute(httpost);
int code = response.getStatusLine().getStatusCode();
if(code < 200 || code >= 300) {
networkError(code);
return null;
}
InputStream instream = response.getEntity().getContent();
Header contentEncoding = response.getFirstHeader("Content-Encoding");
if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip"))
{
instream = new GZIPInputStream(instream);
}
BufferedReader reader = new BufferedReader(new InputStreamReader(instream, "UTF-8"));
StringBuilder builder = new StringBuilder();
for(String line = null; (line = reader.readLine()) != null;) {
builder.append(line).append("\n");
}
return builder.toString();
} catch (Exception x) {
throw new PostException(x);
}
}
protected void networkError(int code) {
}
protected void process(Result result) {
}
protected void error() {
}
@Override
protected Result doInBackground(Paramets... params) {
return null;
}
@Override
protected void onPostExecute(Result result) {
if(result == null) error();
else process(result);
}
}
从上面派生的特定HTTPS AsyncTask(我用它通过OSMA进行反向地理编码):
package using_net;
import android.content.Context;
import android.location.Location;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import globals.Global_Variables;
import logger.AndroidLogger;
import model.Blitz;
import model.NominatimAddress;
import model.SerializableLatLng;
import other.PostException;
/**
* Created by ehog on 2014.06.21..
*/
public class NominatimQuery extends BaseAsyncTask<SerializableLatLng,Void,JSONObject>
{
private NominatimListener _nl;
public interface NominatimListener
{
void got_address(NominatimAddress a);
}
public NominatimQuery(Context context, NominatimListener nl)
{
super(context);
_nl = nl;
}
@Override
protected JSONObject doInBackground(SerializableLatLng... locs)
{
try
{
SerializableLatLng loc = locs[0];
JSONObject nominatim_result;
nominatim_result = new JSONObject(Post(String.format("https://nominatim.openstreetmap.org/reverse?format=json&lat=%s&lon=%s&zoom=19&addressdetails=1",loc.latitude,loc.longitude), null));
JSONObject nominatim_object = nominatim_result.optJSONObject("address");
return nominatim_object;
}
catch (JSONException e)
{
AndroidLogger.PushErrorMessage("Nominatim error! (JSON)");
return null;
}
catch (PostException e)
{
AndroidLogger.PushErrorMessage("Nominatim error! (POST):"+e.toString());
return null;
}
catch (Exception e)
{
AndroidLogger.PushErrorMessage("Nominatim error: "+e.toString());
return null;
}
}
@Override
protected void process(JSONObject nominatim_address)
{
if (_nl != null)
{
NominatimAddress a = new NominatimAddress();
String country_code = nominatim_address.optString("country_code","");
String city = nominatim_address.optString("city","");
String city_district = nominatim_address.optString("city_district","");
String town = nominatim_address.optString("town","");
String village = nominatim_address.optString("village","");
String hamlet = nominatim_address.optString("hamlet","");
String footway = nominatim_address.optString("footway","");
String street = nominatim_address.optString("street","");
String road = nominatim_address.optString("road","");
String house_number = nominatim_address.optString("house_number","");
if (!hamlet.equals(""))
{
a.Settlement = hamlet;
}
else if (!village.equals(""))
{
a.Settlement = village;
}
else if (!town.equals(""))
{
a.Settlement = town;
}
else if (!city.equals(""))
{
a.Settlement = city;
}
else
{
a.Settlement = null;
}
if (country_code.equals("sk") && !city_district.equals(""))
{
a.Settlement = city_district;
}
else if (!city_district.equals(""))
{
a.Settlement = a.Settlement + "-"+city_district;
}
if (!footway.equals(""))
{
a.Address = footway;
}
else if (!street.equals(""))
{
a.Address = street;
}
if (!road.equals(""))
{
a.Address = road;
}
if (!house_number.equals(""))
{
a.Address = a.Address +" "+house_number+".";
}
if (!country_code.equals(""))
{
a.CountryCode = country_code;
}
else
{
a.CountryCode = "empty";
}
_nl.got_address(a);
}
}
protected void networkError(int code) {
if(_nl != null) _nl.got_address(null);
}
protected void error() {
if(_nl != null) _nl.got_address(null);
}
}