android - 获取 HTML 页面源代码而不是 JSON 响应

标签 android json https http-headers

我有一个私有(private)网络服务,我需要在其中通过身份验证和一个 JSONObject 请求。 身份验证完美,响应也正常,但作为响应,我得到了特定 Web 服务实现页面的 HTML 页面源代码。

他们对我发送的 JSONObject 请求有任何问题吗?

请引用下面的代码:

public JSONObject getJSONFromUrl(字符串 url) { 尝试{ DefaultHttpClient httpClient=new DefaultHttpClient();

        HttpPost httppost=new HttpPost(url);
        httppost.setHeader("Authorization", "Basic "+Base64.encodeToString("abc:xyz".getBytes(), Base64.NO_WRAP));

         //Posting request on htt
          httppost.setHeader( "Content-Type", "application/json" );        
          httppost.setHeader("Accept","application/json");
            JSONObject jsonPara = new JSONObject();     
            jsonPara.put("password", "abc");
            jsonPara.put("username", "abc");




            JSONObject jsonobj=new JSONObject();

            jsonobj.put("request", "syncdata/get_country");
            jsonobj.put("para",jsonPara);

            Log.i("jason Object", jsonobj.toString());

            StringEntity se2 = new StringEntity(jsonobj.toString());

            se2.setContentEncoding("UTF-8");
            se2.setContentType("application/json");

            httppost.setEntity(se2);  
        HttpResponse httpResponse=httpClient.execute(httppost);
        HttpEntity httpEntity=httpResponse.getEntity();
        is=httpEntity.getContent();
    }
    catch(UnsupportedEncodingException ae)
    {
    ae.printStackTrace();           
    }
    catch(ClientProtocolException ae)
    {
        ae.printStackTrace();
    }
    catch(IOException ae)
    {
        ae.printStackTrace();
    }
    catch(JSONException e)
    {
        e.printStackTrace();
    }

    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();
        json =sb.toString();
    }
    catch(Exception ae)
    {
        ae.printStackTrace();
    }

    try
    {
        jObj=new JSONObject(json);
    }
    catch(JSONException e)
    {
    e.printStackTrace();    
    }

    return jObj;
}

另外,我如何确认我得到的响应是 JSON 或其他格式(除了调试),以及我是否得到了我实际应该得到的正确响应。

最佳答案

引用此代码。

希望对你有所帮助...

主 Activity .java

    public class MainActivity extends Activity {

InputStream is=null;
String result=null;
String line=null;

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

try
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.2.2/text.php");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Log.e("Pass 1", "connection success ");
}
catch(Exception e)
{
Log.e("Fail 1", e.toString());
Toast.makeText(getApplicationContext(), "Invalid IP Address",Toast.LENGTH_LONG).show();
}    

try
{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
result = sb.toString();
Log.e("Pass 2", "connection success ");
}
catch(Exception e)
{
Log.e("Fail 2", e.toString());
}    

try
{
JSONArray JA=new JSONArray(result);
JSONObject json= null;
final String[] str1 = new String[JA.length()];       
for(int i=0;i<JA.length();i++)
{
json=JA.getJSONObject(i);
str1[i]=json.getString("name");
}

final AutoCompleteTextView text = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView1);
final List<String> list = new ArrayList<String>();

for(int i=0;i<str1.length;i++)
{
list.add(str1[i]);
}

Collections.sort(list);

ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(getApplicationContext(),
                android.R.layout.simple_spinner_item, list);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
text.setThreshold(1);
text.setAdapter(dataAdapter);

text.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) {
// TODO Auto-generated method stub
Toast.makeText(getBaseContext(), list.get(arg2).toString(), Toast.LENGTH_SHORT).show();
}
});

}
catch(Exception e)
{
Log.e("Fail 3", e.toString());
}
}

文本.php

<?php
$host='127.0.0.1';
$uname='root';
$pwd='password';
$db='android';
$con = mysql_connect($host,$uname,$pwd) or die("connection failed");
mysql_select_db($db,$con) or die("db selection failed");
$r=mysql_query("select * from class",$con);
while($row=mysql_fetch_array($r))
{
$cls[]=$row;
}
print(json_encode($cls));
mysql_close($con);
?>

关于android - 获取 HTML 页面源代码而不是 JSON 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11758825/

相关文章:

android - CalendarView android 中的小数字

json - 尝试循环散列内的数组时未收到 HASH 引用错误

https - Google Cloud 全局转发 : Invalid value for field resource. IPAddress

java - libgdx 不会绘制 Sprite 或动画

android - EditText 中双值的双向数据绑定(bind)

android - 每次我尝试导出签名的 apk 时,ADT 都会排除一堆类

iis - 使用 appcmd 添加 ssl 绑定(bind)时出错

ios - swift 3 中从数组到字典的 JSON 解析问题

javascript - JSONP 使用 - 范围或异步问题?使用 JQuery

ssl - 使用 docker 设置安全的 Jenkins master