我是Java和Android开发的新手,并尝试创建一个简单的应用程序,它应该联系Web服务器并使用http get将一些数据添加到数据库.
当我使用计算机中的Web浏览器进行呼叫时,它可以正常工作.但是,当我在Android模拟器中执行运行应用程序的调用时,不会添加任何数据.
我已将Internet权限添加到应用程序的清单中.Logcat不会报告任何问题.
任何人都可以帮我弄清楚什么是错的?
这是源代码:
package com.example.httptest;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
public class HttpTestActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView tv = new TextView(this);
setContentView(tv);
try {
URL url = new URL("http://www.mysite.se/index.asp?data=99");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.disconnect();
tv.setText("Hello!");
}
catch (MalformedURLException ex) {
Log.e("httptest",Log.getStackTraceString(ex));
}
catch (IOException ex) {
Log.e("httptest",Log.getStackTraceString(ex));
}
}
}
Run Code Online (Sandbox Code Playgroud) 随着Android 5.1的发布,看起来所有Apache http的东西都被弃用了.看文档是没用的; 他们都说
This class was deprecated in API level 22.
Please use openConnection() instead. Please visit this webpage for further details.
这是第一次阅读它时没关系,但是当每个被弃用的类都说明了这一点时,它没那么有用.
总之,什么是类的替代喜欢HttpEntity,特别是StringEntity和MultipartEntity?我替换BasicNameValuePair了我自己的Android Pair<T, S>类实现,它看起来URLEncoder.encode是一个很好的替代品URLEncodedUtils,但我不知道该怎么做HttpEntity.
编辑
我决定重新编写网络内容.要尝试使用Retrofit和OkHttp
编辑
认真看看将你的通话和东西转换为Retrofit.很漂亮.我很高兴我做到了.有一些障碍,但它很酷.